将字符串ID与BSON :: ObjectId进行比较

我有一个由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吗? 如果是这样,怎么样?

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

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

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

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

使用轻便摩托车的Mongoid 3:

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

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

 BSON::ObjectId.from_string('506144650ed4c08d84000001') 
 collection.delete_one({"_id"=>BSON::ObjectId(params['id'])}) 

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