Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to ObjectID in MongoDB

I am developing an API using Codeigniter and MongoDB. In some parts of the database I have saved the ID of an image in ObjectID format instead of a string. Now I got an ID in string format and I need to query the database using it.

How can I "convert" a string to an ObjectID so that I can do the query?

From this:

34234234234234234234 

To this:

ObjectID("34234234234234234234") 

UPDATE

I found a solution. Just do this new MongoId('34234234234234234234');

like image 580
Jonathan Clark Avatar asked Oct 19 '11 17:10

Jonathan Clark


People also ask

How does MongoDB generate ObjectId?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The 5 byte "random value" does not appear to be random.

Can MongoDB _id be a string?

Yes, you can use a string as your _id.

What is ObjectId in MongoDB?

An ObjectId is a 12-byte BSON type having the following structure − The first 4 bytes representing the seconds since the unix epoch. The next 3 bytes are the machine identifier. The next 2 bytes consists of process id. The last 3 bytes are a random counter value.

How is ObjectId generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.


2 Answers

Using mongoose:

var mongoose = require('mongoose'); var objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa'); 

Using native driver (https://stackoverflow.com/a/21076589/3377073)

var ObjectId = require('mongodb').ObjectId; doc._id = new ObjectId(doc._id); // wrap in ObjectID 
like image 79
Nicolas Del Valle Avatar answered Sep 24 '22 16:09

Nicolas Del Valle


You just need to require the ObjectId function from your mongo.

ObjectId = require('mongodb').ObjectID; 

Then you can use it like that:

ObjectId("34234234234234234234") 
like image 26
julien bouteloup Avatar answered Sep 23 '22 16:09

julien bouteloup