Find Mongo Document By ID Using The PHP Library
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!
Pingback: Community News: Recent posts from PHP Quickfix (06.15.2016) – SourceCode
Hi lorna, this version of the mongo php extension is deprecated?
Hi, I have a question. This is really true way to handle ids in Mongodb? It looks like a nightmare.