Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare string ID to BSON::ObjectId

I have an array of made up of type BSON::ObjectId and I want it to compare against some IDs 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 is not working as the types are different, can I turn my string into a BSON::ObjectId? If so, how?

like image 633
Finnnn Avatar asked Sep 25 '12 08:09

Finnnn


People also ask

What is ObjectId in BSON?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.

Is MongoDB ObjectId a string?

A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length.

How do you check if the ObjectId is valid or not?

If you do not conditionally test whether expected objectID is valid, you will need to catch the error. Since findOne({ _id: null }) and findOne({ _id: undefined }) are completely valid queries (doesn't throw error), isValidObjectId(undefined) and isValidObjectId(null) will return true.


2 Answers

Mongoid 2.x with 10gen's driver:

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

Mongoid 3 with moped:

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

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

BSON::ObjectId.from_string('506144650ed4c08d84000001')
like image 172
Sergio Tulentsev Avatar answered Sep 22 '22 17:09

Sergio Tulentsev


You can use BSON::ObjectId(@my_id_as_a_string) for representation your id as BSON::ObjectId

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

like image 31
Andrei Subbota Avatar answered Sep 18 '22 17:09

Andrei Subbota