Created
October 10, 2012 03:27
-
-
Save danmaispace/3863005 to your computer and use it in GitHub Desktop.
MongoDB: find by MongoDB ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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