[英]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. 我正在尝试使用标准类型ObjectID的_id检索存储在MongoDB中的文档。 I have the _id represented as a string. 我将_id表示为字符串。 In this example it's "4ec064e406a6f1205a000001" 在这个例子中它是“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. 我意识到这是一个BSON ObjectID,我尝试了一些不同的方法来使用bson gem生成正确的对象,但我无法让它工作。 I also tried to change one of the object's _id to a standard Int32 using similar code and it worked fine. 我也尝试使用类似的代码将对象的_id中的一个更改为标准的Int32,并且它工作正常。 I don't know how to create the right ObjectID object to use with this query. 我不知道如何创建用于此查询的正确ObjectID对象。
Thanks! 谢谢!
以下是将字符串转换为BSON ObjectID的正确语法:
collection.find_one({:_id => BSON::ObjectId("4ec064e406a6f1205a000001")})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.