6

I want to get a record by its _id like this:

db.user.find({_id : ObjectId("53a095aa4568cb1fef93f681")})

As you can see the record exists:

mongoDB record by _id

I think my way is correct according to:

So what's wrong with my code? I'm using RoboMongo.

Community
  • 1
  • 1
ehsan shirzadi
  • 4,709
  • 16
  • 69
  • 112
  • 2
    As answered below you inserted your documents without using the default MongoDB ObjectId type, probably a bug in your code or something – Sammaye Jun 26 '14 at 10:49

4 Answers4

7

Your _id field isn't an ObjectId it is just a String.

This should work:

db.user.find({_id : "53a095aa4568cb1fef93f681"})

Mongodocs: https://docs.mongodb.com/v3.2/reference/method/ObjectId/

Zarathustra
  • 2,853
  • 4
  • 33
  • 62
  • 3
    OMG! What a silly mistake I've made! Waste of my time for hours :| Thanks buddy... – ehsan shirzadi Jun 26 '14 at 11:05
  • 1
    Well ... how many hours I have spend with stupid mistakes where mongodb was involved... – Zarathustra Jun 26 '14 at 11:48
  • @Zarathustra, why i have documents with string and sometimew with object, i remember i've had some of record with a GUI, but i dont remember well, anyway where i can set that, and what is the best option ? – stackdave Nov 19 '16 at 15:43
  • @stackdave to use the autogenerated ObjectId. You may find the documents where _id is a string by a query. You may learn something from this answer http://stackoverflow.com/a/30975037/1248724 – Zarathustra Nov 21 '16 at 10:42
4

If you are using python, Try this,

from bson import ObjectId
db.user.find({_id : ObjectId("53a095aa4568cb1fef93f681")})
Shirantha Madusanka
  • 1,461
  • 1
  • 11
  • 16
1

Sometime it is right to find _id as a str, sometime it is right to find _id as an ObjectId, it depends on where you are.

a. NoSQLBooster/Pymongo:

db.user.find({_id : ObjectId("53a095aa4568cb1fef93f681")})

b. Robo3T/RoboStudio

db.user.find({_id : "53a095aa4568cb1fef93f681"})
K. Symbol
  • 3,330
  • 1
  • 21
  • 22
0

Using:

{ _id: new ObjectId('53a095aa4568cb1fef93f681')

It is what worked for me. Try adding new ObjectID('53a095aa4568cb1fef93f681'). It gave me error without using new. Hope that helps

DSDmark
  • 1,045
  • 5
  • 11
  • 25