Convert string to ObjectID in MongoDB

Jonathan Clark picture Jonathan Clark · Oct 19, 2011 · Viewed 92.6k times · Source

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');

Answer

Nicolas Del Valle picture Nicolas Del Valle · Jan 20, 2016

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