My new job at IBM is as a development support staff member. That means I spend most of my time working with databases. In my workflow, I spent some time with MongoDB - which is a document database. But I encountered some problems in retrieving records by ID. The code below is the final version, I can quote it directly when encountering similar problems in the future. If you need it too, I hope the following will be helpful to you.
MongoDB and IDs
When I inserted data into a collection, I did not set the _id field; if this field is empty, then MongoDB will automatically generate an ID to use, which is a problem for me It's very good. However, this creates problems when I use identifiers generated by MongoDB.
If I use db.posts.find() to retrieve my data (my collection is called posts), then the data looks like this:
{ "_id" : ObjectId("575038831661d710f04111c1") , ...
So if I want to retrieve the data using the ID, I also need to include the ObjectId method to access the ID.
Using PHP library
When I used PHP to do this, I didn’t find a suitable example of using this new PHP library (however, this class library is indeed a very good one library). In previous versions, this library was implemented using a class called MongoID. But I know that's not what I want - but I can actually inspect the document through this class. So it's useful to know this method if you can only find examples from previous code.
By passing an ID to MongoDB using this PHP library, you need to construct a MongoDBBSONObjectID instance. The following example retrieves documents in a blog by document ID.
$post = $posts->findOne(["_id" => new MongoDBBSONObjectID($id)]);
Then, I'm going to update this record - this blog post is in this record It also contains embedded comments, so add an array to the comments collection in the record with the _id,
$result = $posts->updateOne( ["_id" => new MongoDB\BSON\ObjectID($id)], ['$push' => [ "comments" => $new_comment_data ] ]);
Finally, I hope this article is helpful to everyone. Thank you for your support of this site!
For more PHP libraries, please pay attention to the PHP Chinese website for related articles on how to query document IDs in Mongodb!