How do I search for an object by its ObjectId in the mongo console?

If you're using Node.js:

var ObjectId = require('mongodb').ObjectId; 
var id = req.params.gonderi_id;       
var o_id = new ObjectId(id);
db.test.find({_id:o_id})

Edit: corrected to new ObjectId(id), not new ObjectID(id)


Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.

Documentation is here

> db.test.insert({x: 1})

> db.test.find()                                               // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }      

> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c"))           // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

You Have missed to insert Double Quotes. The Exact Query is

db.theColl.find( { "_id": ObjectId("4ecbe7f9e8c1c9092c000027") } )

Even easier, especially with tab completion:

db.test.find(ObjectId('4ecc05e55dd98a436ddcc47c'))

Edit: also works with the findOne command for prettier output.

Tags:

Mongodb