Compare string id with BSON :: ObjectId

I have an array consisting of a type BSON::ObjectId, and I want it to be compared with some identifiers as strings.

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

This does not work, since the types are different, can I turn my string into BSON::ObjectId? If so, how?

+5
source share
3 answers

You can use BSON::ObjectId(@my_id_as_a_string)to represent your identifier asBSON::ObjectId

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

+5
source

Mongoid 2.x with 10gen driver:

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

Mongoid 3 with a moped:

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

Mongoid 4 (moped) / Mongoid 5 (mongo):

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

0

All Articles