Over a million developers have joined DZone.

Finding Mongo Document IDs Using the PHP Library

DZone's Guide to

Finding Mongo Document IDs Using the PHP Library

This quick how-to shows how to scour MongoDB to find documents. This method uses the MongoDB PHP library to make it happen.

· Database Zone ·
Free Resource

Running out of memory? Learn how Redis Enterprise enables large dataset analysis with the highest throughput and lowest latency while reducing costs over 75%! 

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, and 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!

Related Refcard: MongoDB

Running out of memory? Never run out of memory with Redis Enterprise databaseStart your free trial today.

database ,library ,document database ,php ,mongodb

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}