Convert string to ObjectID in MongoDB

2020-01-27 07:21发布

问题:

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

回答1:

http://api.mongodb.org/java/2.6.5/org/bson/types/ObjectId.html

Here, you can see that there is a constructor ObjectId with single String parameter. So, can't it be useful to you ?



回答2:

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

ObjectId = require('mongodb').ObjectID;

Then you can use it like that:

ObjectId("34234234234234234234")


回答3:

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


回答4:

If you are using Meteor

var id = new Mongo.ObjectID("34234234234234234234");


回答5:

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.



回答6:

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