Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

I've found this question answered for C# and Perl, but not in the native interface. I thought this would work:

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

The query returned no results. I found the 4ecbe7f9e8c1c9092c000027 by doing db.theColl.find() and grabbing an ObjectId. There are several thousand objects in that collection.

I've read all the pages that I could find on the mongodb.org website and didn't find it. Is this just a strange thing to do? It seems pretty normal to me.

like image 831
jcollum Avatar asked Nov 22 '11 20:11

jcollum


1 Answers

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 } 
like image 136
Tyler Brock Avatar answered Oct 17 '22 05:10

Tyler Brock