Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not find a record by it's _id in mongoDB

Tags:

mongodb

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:

  • Why am I unable to find a record by _id in mongodb
  • how do I search for an object by its ObjectId in the console?
  • Is it ok to use Mongo's "Object ID" as its unique identifier? If so, how can I convert it to a string and look it up by string?

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

like image 752
ehsan shirzadi Avatar asked Jun 26 '14 10:06

ehsan shirzadi


People also ask

What is meaning if _id in MongoDB?

What Is MongoDB ObjectID? As MongoDB documentation explains, "ObjectIds are small, likely unique, fast to generate, and ordered." The _id field is a 12-byte Field of BSON type made up of several 2-4 byte chains and is the unique identifier/naming convention MongoDB uses across all its content.

Where is MongoDB record by ID?

MongoDB provides a function with the name findById() which is used to retrieve the document matching the 'id' as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified 'id', it returns null.

Can we set _id in MongoDB?

_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.


1 Answers

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/

like image 84
Zarathustra Avatar answered Oct 10 '22 20:10

Zarathustra