I want to get a record by its _id
like this:
db.user.find({_id : ObjectId("53a095aa4568cb1fef93f681")})
As you can see the record exists:
I think my way is correct according to:
So what's wrong with my code? I'm using RoboMongo.
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.
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.
_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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With