Include MongoDB _id in an ObjectID object using Ruby to get a unique record

I am trying to get a document stored in MongoDB using my _ID of the standard ObjectID type. I have _id represented as a string. In this example, it is "4ec064e406a6f1205a000001"

So I:

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 understand that this is the BSON ObjectID, and I tried to use different ways to use bson pearls to create the desired object, but I cannot get it to work. I also tried changing one of the _id objects to standard Int32 using similar code, and it worked fine. I do not know how to create the correct ObjectID object for use with this request.

Thanks!

+4
source share
1 answer

Here is the correct syntax for entering a string in the ObjectID of a BSON:

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

Source: https://habr.com/ru/post/1381054/


All Articles