mongo-php-library: Wrong Documentation: findOne(['_id' =>new MongoDB\BSON\ObjectID('94301')]) instead of findOne(['_id' => '94301'])

Hi, it seems to me that if we’d like to search by the internal _id we have to use “new MongoDB\BSON\ObjectID($_id)” instead of using the _id just as string:

E.g. instead of: $document = $collection->findOne(['_id' => '94301']);

we have to do this: $document = $collection->findOne(['_id' => new MongoDB\BSON\ObjectID('94301')]);

Found here: http://lornajane.net/posts/2016/find-mongo-document-by-id-using-the-php-library

If this is right could somebody update the docs?

Thanks, Olaf

E.g. docs for “Finding One Document”: mongodb_phplib_docs

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 3
  • Comments: 15 (4 by maintainers)

Most upvoted comments

six months in and this hasn’t been solved yet… it took me an 2 hours to work out that there was an error in the documentation.

This was actually added to the documentation a few weeks back (note the last sentence in the quote below).

When evaluating query criteria, MongoDB compares types and values according to its own comparison rules for BSON types, which differs from PHP’s comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class in the driver (e.g. use MongoDB\BSON\ObjectID to match an ObjectId).

Also, note that this is not a functionality that has recently been added to the driver or the library. This has always worked. The way that the _id field works in MongoDB has nothing to do with the client code. You have always been able to use any BSON type as _id for your documents, as long as the value is unique across your collection. The type you use in your documents determines which value you have to use in your queries. If you use strings as _id you have to query with string IDs, if you use ObjectId you have to query using MongoDB\BSON\ObjectID, and so on.

I think this is more of a misunderstanding in how the MongoDB _id field works, rather than an issue with the documentation for this library. However, it wouldn’t hurt to include it somewhere just to remove any possibility for confusion.

I’ve just test it by creating a document that contains the _id as string. It could be retrieved by just passing the _id to the findOne() function as you said and as it described in the docs. Makes sense 😉 Thank you for the hint!

So this is not an issue but I think without this knowledge this is a kind of needless pitfall, especially for beginners like me. Maybe a hint in the docs that for documents that were stored using the auto generated _id we have to pass the _id as ObjectId to be able to retrieve it might be helpful for others.

Thanks, Olaf