RedNax
RedNax

Reputation: 1507

How can I retrieve a document by _id?

I'm trying to retrieve a document when I have an object id - however, the query does not work.

@collection = @db.collection('Mylist')
@result = @collection.find({"_id" => params[:id]})

I've tried variations of the query - it always yields empty - however when I try a query on the collection such as below, that would work.

@result = @collection.find({"Exist" => "True"}) 

Why? It is strange that complex queries work but a simple query by _id returns nothing.

If possible, I don't want to use MongoMapper.

Thanks

Upvotes: 4

Views: 1238

Answers (3)

Victor S
Victor S

Reputation: 5132

find(:_id => BSON::ObjectID(params[:id])

Upvotes: 3

RedNax
RedNax

Reputation: 1507

Found it - you need to wrap it like this -

find({"_id" => Mongo::ObjectId(params[:id])}) 

Upvotes: 5

Rubycut
Rubycut

Reputation: 1646

This would also work: @coll.find_one(ObjectID.from_string(params[:id]))

Upvotes: 2

Related Questions