Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a document with ObjectID in mongoDB

When I inserted some documents into a collection (without an ObjectID) mongoDB adds its own ObjectIDs.

I want to query a document by its unique ObjectID.

$db->collection_name->find(array('_id'=>'4e49fd8269fd873c0a000000'))); 

It does not work either with prefix of MongoID or ObjectID in front of '4e49fd8269fd873c0a000000'.

What is the proper way to query by ObjectID with mongoDB in PHP?

like image 681
jwchang Avatar asked Aug 16 '11 06:08

jwchang


People also ask

What is the use of ObjectID in MongoDB?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.

How do I search multiple values in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.


2 Answers

Pretty sure you have to use a MongoId object, eg

$item = $collection->findOne(array(     '_id' => new MongoId('4e49fd8269fd873c0a000000'))); 

The notes on the Querying page are a little obtuse but it does mention...

Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attepting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array

like image 154
Phil Avatar answered Oct 13 '22 07:10

Phil


I think now the API changes to MongoDB\BSON\ObjectID, also you can use [] to denote an array in PHP 5.4+, so it should be:

$item = $collection->findOne(['_id' => new MongoDB\BSON\ObjectID( idToken )]); 

based on Phil's answer.

like image 23
coolgod Avatar answered Oct 13 '22 09:10

coolgod