Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
242 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...