62

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")
Cristik
  • 30,989
  • 25
  • 91
  • 127
Jonathan Clark
  • 19,726
  • 29
  • 111
  • 175

9 Answers9

60

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
Nicolas Del Valle
  • 1,384
  • 15
  • 20
46

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

ObjectId = require('mongodb').ObjectID;

Then you can use it like that:

ObjectId("34234234234234234234")
julien bouteloup
  • 3,022
  • 22
  • 16
6

If you are using Meteor

var id = new Mongo.ObjectID("34234234234234234234");
Alex K
  • 6,737
  • 9
  • 41
  • 63
4

you can now convert string to objectId on mongodb 4.0 and above. there is new feature to convert from string id to objectId

here you can see the documentation $toObjectId

Carlos
  • 458
  • 12
  • 23
0

or better use

var mongodb = require(‘mongodb’); //this might have been defined at the beginning of your code.
//now use it
query = {_id:mongodb.ObjectId('569ed8269353e9f4c51617aa')};

and the rest is the same.

Gelineau
  • 2,031
  • 4
  • 20
  • 30
Manna
  • 27
  • 4
0

(Extracted from the question)


I found a solution. Just do this:

new MongoId('34234234234234234234');
Cristik
  • 30,989
  • 25
  • 91
  • 127
0

If you are in an aggregation you can use the following :

{
   $toObjectId: <expression>
}

Which is a shortcut for :

{ $convert: { input: <expression>, to: "objectId" } }

From mongodb documentation

Kyofa
  • 548
  • 4
  • 16
-2
import { ObjectId } from 'mongodb'
const query  = {"_id":ObjectId(req.params.productId)}
-4

mongo DB version v3.6.3

how to save string input to MongoDB ObjectId on express controller code

const mongoose = require('mongoose');
var ObjectId = require('mongodb').ObjectId;
user: mongoose.Types.ObjectId(req.body.user)
console.log(user, typeof(user))
Mr Coder
  • 507
  • 3
  • 13