Why am I unable to find a record by _id in mongodb
Solution 1
Try db.Employee.find({_id:ObjectId("4e209564203d83940f000006")}
Solution 2
you can wrap your id around a ObjectID wrapper. This tells mongo db your looking for a specific column the _id column.
var ObjectID=require('mongodb').ObjectID;
then do
collection.findOne({_id: ObjectID(id)},function(err,user){ //blah blah}
![Scott Szretter](https://i.stack.imgur.com/JS71d.jpg?s=256&g=1)
Scott Szretter
As. Director or Information Technology / Developer N1VAN www.508tech.com Apache / PHP / MySQL IIS / ASP.NET / MS-SQL Flex / Flash Builder / Actionscript .NET / C# / VB / MVC JavaScript / XML / HTML / DHTML Java / Objective-C Enterprise Networking / Server & Workstation Hardware / Storage VMWARE / VEEAM
Updated on June 04, 2022Comments
-
Scott Szretter about 2 years
I am trying to find a record in mongoDB by it's MongoID "_id" field. I have found examples on how to do it, but can not get it to work. Example:
$recID = "010101010101011"; //would be a valid mongodb _id $recID = new MongoId((string)$recID); // I have tried it without the (string) cast too $cursor = $this->Collection->findOne(array('_id' => $recID)); print_r($cursor);
It outputs:
MongoCursor ( )
Nothing inside.
I have verified everything else is working by changing the "_id" above to a different field such as "firstName" and passing in a first name and I get back valid data.
Why does this not work?
I have even tried searching with $recID as a string, no difference.
Here is what happens from the mongo shell (though I am not sure if I am querying properly):
> > db.Employee.find({login:"myperson"}) { "_explicitType" : "project.Employee", "_id" : ObjectId("4e209564203d83940f0000 06"), "active" : true, "addedDate" : "07/15/2011 15:29:21", "domain" : "xxx", "id" : ObjectId("4e209564203d83940f000006"), "lastLogin" : "07/20/2011 19:13:36 ", "login" : "myperson", "name" : "My Person", "pw" : "", "ulevel" : 9999 } > db.Employee.find({id:"4e209564203d83940f000006"}) > db.Employee.find({_id:"4e209564203d83940f000006"}) >
Notice nothing returned for id or _id.
-
Scott Szretter almost 13 yearsOk, that works from the shell, but it's not working from php using my code above.
-
Scott Szretter almost 13 yearsSo I reviewed my php code again and it's working now. I have no idea why. It was good learning about the mongodb shell though.