5

我有一个由类型组成的数组,BSON::ObjectId我希望它与一些 ID 作为字符串进行比较。

if my_array_of_BSON_ObjectIds.include?(@my_id_as_a_string)
   # delete the item from the array
else
   # add the item to the array as a BSON::ObjectId
end

这不起作用,因为类型不同,我可以把我的字符串变成一个BSON::ObjectId吗?如果是这样,怎么做?

4

4 回答 4

14

带有 10gen 驱动程序的 Mongoid 2.x:

BSON::ObjectId.new('506144650ed4c08d84000001')

带轻便摩托车的 Mongoid 3:

Moped::BSON::ObjectId.from_string('506144650ed4c08d84000001')

Mongoid 4(轻便摩托车)/ Mongoid 5/6/7(mongo):

BSON::ObjectId.from_string('506144650ed4c08d84000001')
于 2012-09-25T08:20:42.433 回答
5

您可以将BSON::ObjectId(@my_id_as_a_string)您的 id 用于表示BSON::ObjectId

参考http://api.mongodb.org/ruby/current/BSON.html#ObjectId-class_method

于 2012-09-25T08:22:42.440 回答
0
collection.delete_one({"_id"=>BSON::ObjectId(params['id'])})

这对我有用,它成功地从数据库中删除了记录

于 2016-06-21T10:12:33.197 回答
0

有一个更短的方法:

BSON::ObjectId("id_here")

但是对于您的情况,在比较之前将对象简单地映射到 id 会更容易:

if my_array_of_BSON_ObjectIds..map(&:to_s).include?(@my_id_as_a_string)
于 2021-08-18T05:48:16.357 回答