Find Mongo Document By ID Using The PHP Library

My new job as a Developer Advocate with IBM means I get to play with databases for a living (this is the most awesome thing ever invented, seriously). On my travels, I spent some time with MongoDB which is a document database – but I ran into an issue with fetching a record by ID so here’s the code I eventually arrived at, so I can refer to it later and if anyone else needs it hopefully they will find it too.

MongoDB and IDs

When I inserted the data to the collection, I did not set the _id field; if this is empty, MongoDB will just generate an ID and use that which is fine by me. My issues arose when I wanted to then fetch that data using that generated identifier.

If I inspect my data by using db.posts.find() (my collection is called posts), then the data looks like this:

{ "_id" : ObjectId("575038831661d710f04111c1"), ...

So if I want to fetch by ID, I need to include that ObjectId function call around the ID.

Using the PHP Library

When I came to do this with PHP, I couldn’t find an example of using the new MongoDB PHP Library that used the ID in this way (but it’s a good library, use it). Older versions of this library used a class called MongoID and I knew that wasn’t what I wanted – but had I checked the docs for that, I’d have found that they have been updated to point to the new equivalent so this is also very useful to know if you can only find older code examples!

To pass an ID to MongoDB using the PHP Library, you will need to construct a MongoDB\BSON\ObjectID. My example was blog posts and to fetch a record by its ID, I used:

    $post = $posts->findOne(["_id" => new MongoDB\BSON\ObjectID($id)]);

Later I updated the record – the blog post included nested comments in the record, so to add an array to the comments collection of a record whose _id I knew, I used this code:

    $result = $posts->updateOne(
        ["_id" => new MongoDB\BSON\ObjectID($id)],
        ['$push' => [
            "comments" => $new_comment_data

Hopefully this gives you a pointer on using the generated IDs in MongoDB from the PHP library and saves you at least as much time as I lost trying to figure this out!

3 thoughts on “Find Mongo Document By ID Using The PHP Library

  1. Pingback: Community News: Recent posts from PHP Quickfix (06.15.2016) – SourceCode

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.