Skip to content

Instantly share code, notes, and snippets.

@danmaispace
Created October 10, 2012 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danmaispace/3863005 to your computer and use it in GitHub Desktop.
Save danmaispace/3863005 to your computer and use it in GitHub Desktop.
MongoDB: find by MongoDB ID
How to find a document by using MongoDB ID
published by chao on Thu, 01/05/2012 - 22:48
Categories:
TechnologyDatabase
MongoDBObjectID
When obtain the ID from request parameter: 4eec06b12dacbe7275000005, it is string, however, the format of _id is ObjectID. String and ObjectID are different types. MongoDB driver provides a function to serialize the 12 character string into a ObjectID type.
var ObjectId = collection.db.original.bson_serializer.ObjectID;
collection.findOne({'_id': ObjectId(idString)}, console.log);
Another way to do it:
var ObjectId = require('mongodb').BSONPure.ObjectID;
collection.findOne({_id: ObjectId(idString)}, console.log);
In MongoDB shell:
> db.foo.findOne({_id: ObjectId(idString)})
Be carefule, it’s ObjectId not ObjectID.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment