1

I want to perform full text search on my collection. Since i am using mongo 2.4 I would like to do it with mongodb's text command

The way to do it in mongo's console is (as per mongo's official docs.)

db.collection.runCommand( "text", { search: <string> })

It returns expected results.

Now, I want to achieve same in ruby/rails. I am using mongo gem version 1.8.4

As per their change log/history there is a support for new MongoDB 2.4 index types

But how can i run the text command on a collection with ruby.

I went through this blog post. But it did'nt help

Update:

I tried,

  command = BSON::OrderedHash.new
  command['find'] = collection
  command['text'] = {'search' => 'string'}
  result = @db.command(command)

But it gives

Database command 'find' failed: (ok: '0.0'; errmsg: 'no such cmd: find'; bad cmd: '{"find"=>"project", "text"=>{"search"=>"string"}}').

Update 2:

Similar exists for php. I am looking ruby's equivalent for the same.

3 Answers 3

2

You only need to use BSON::OrderedHash with Ruby 1.8. If you're running Ruby 1.9 or greater you can use the following syntax to create/query on a text index.

require 'mongo'
include Mongo

client = MongoClient.new
db = client['my_database']
coll = db['my_collection']

# create a text index
coll.ensure_index({:field_name => Mongo::TEXT})

# run a text query
db.command({:text => 'my_collection', :search => 'search string'})
db.command({:text => 'my_collection', :search => 'search string', :filter => {:foo => 'bar'}})
Sign up to request clarification or add additional context in comments.

Comments

1

I used,

  command = {}
  command["text"] = collection_name
  command["search"] = "search_string"
  result = @db.command(command)

looks like it works. I will wait for other answers though.

Comments

1

I have no working mongodb installation here, but the following should do the trick:

command = OrderedHash.new
command['text'] = <collectionname>
command['search'] = <string>
result = @db.command(command)

Hope this helps.

3 Comments

I tried this before. Dint work. how does it know what collection to search on. the command() is on db object.
That dint work. undefined method 'command' for #<Mongo::Collection:0xa181910>
@Mashit sorry I messed things up; finally I updated an answer with the code that worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.