The PHP library queries ID for documents in Mongodb

  • 2020-06-07 05:30:13
  • OfStack

One of my new jobs at IBM is as a development support staff. That means I spend most of my time working with databases. In my workflow, I spend some time with MongoDB -- a document database. But I ran into a few problems with retrieving records through ID. The following code is the final version and I can refer to it directly if I encounter similar problems in the future. If you need it, I hope it will help you.

MongoDB and IDs

When I insert data into a collection, I do not set the _id field; If this field is empty, MongoDB will automatically generate 1 ID to use, which is great for me. However, this causes problems when I use the identifiers generated by MongoDB.

If I use db.posts.find () to retrieve my data (my collection is called posts), the data will open as follows:

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

Therefore, if I want to retrieve data using ID, I also need to include the ObjectId method to access ID.

Using PHP library

When I do this with PHP, I don't have a good example to use with the new PHP library (but it's a pretty good 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 check the document with this class. So it's useful to know about 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 an instance of MongoDB\BSON\ObjectID. The following example is to retrieve documents from a blog through Id for documents.

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

Then, I'm going to update this record -- this blog post also has embedded comments in this record, so add an array to the collection of comments in the record that gets _id,


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

Finally, I hope this article will be helpful to you. Thank you for your support!


Related articles: