user636044
user636044

Reputation:

Turn MongoDB _id into an ObjectID object using Ruby to Retrieve Unique Record

I'm trying to retrieve a document stored in MongoDB using its _id of the standard type ObjectID. I have the _id represented as a string. In this example it's "4ec064e406a6f1205a000001"

So I do:

require 'mongo'

connection = Mongo::Connection.new("localhost", 27017).db("store")
collection = connection.collection("products")

id = '4ec064e406a6f1205a000001'

# What should the following line be? This doesn't work.
collection.find_one("_id" => Mongo::ObjectID.from_string(id))

I realize this is a BSON ObjectID and I tried some different ways of using the bson gem to generate the right object but I can't get it to work. I also tried to change one of the object's _id to a standard Int32 using similar code and it worked fine. I don't know how to create the right ObjectID object to use with this query.

Thanks!

Upvotes: 5

Views: 3317

Answers (1)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

Here's the correct syntax for taking a string into a BSON ObjectID:

collection.find_one({:_id => BSON::ObjectId("4ec064e406a6f1205a000001")})

Upvotes: 9

Related Questions