Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - findOne by _id returns null in shell

When I run a simple findOne to get a document with no filter, I get this:

mongos> db.mycollection.findOne({},{_id:1})
{ "_id" : "1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9" }

But when I feed that _id back in as a filter, I get no results:

mongos> db.mycollection.findOne({ "_id" : "1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9" } )
null

Why is this? When I search on other fields I am able to get a result, but searching with _id returns nothing.

Of note is that these documents include a nested object with it's own _id. Searching using this nested._id field also returns nothing.

My environment: 2 shard mongoDB 3.4 running on Centos 7. Each replica set has 3 members and everything looks healthy.

like image 578
msgisme Avatar asked Sep 13 '25 09:09

msgisme


1 Answers

Check MongoDB and make sure that your _id fields are all ObjectIds rather than plain strings. Basically when you inserting document with custom Id make sure you are passing object into "_id" field. For me the following would work ...

mongos> db.mycollection.findOne({},{_id:1})
{ "_id" : ObjectId("1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9") }

and findOne by _id ...

mongos> db.mycollection.findOne({ "_id" : ObjectId("1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9") } )
{ "_id" : ObjectId("1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9"), "blahh" : "val"}
like image 115
Slava Ivanov Avatar answered Sep 15 '25 14:09

Slava Ivanov