One of my new jobs at IBM is a development logistics staff. That means I spend most of my time dealing with the database. In my workflow, I spent some time on MongoDB-this is a document database. But I ran into some problems with the ID to retrieve the record. The following code is the final version, and I can refer to it directly after encountering similar problems. If you also need to, hope that the following help.
MongoDB and IDs
When I insert data into a collection, I do not set the _id field; If this field is empty, then MongoDB will automatically generate an ID to use, which is very good for me. However, when I use the identifier generated by MongoDB, there is a problem.
If I use Db.posts.find () to retrieve my data (my collection is called posts), then the data is opened as follows:
{"_id": ObjectId ("575038831661D710F04111C1"), ...
So, if I want to retrieve the data by ID, I also need to include the Objectid method to access the ID.
Using the PHP Library
When I used PHP to do this, I didn't find a suitable example when I used the new PHP class library (but this class library is really a very good library). In previous releases, this library was implemented using a class called Mongoid. But I know it's not what I want--but I can actually check the document through this class. So if you can only find examples in your previous code, it's still useful to know this method.
By passing an ID to MongoDB with this PHP library, you need to construct a Mongodb\bson\objectid instance. The following example retrieves a document from a blog through the ID of the document.
$post = $posts->findone (["_id" => new Mongodb\bson\objectid ($id)]);
Then I'm going to update this record--this blog post contains embedded comments in this record, so add an array to the comments collection in the record that gets _id.
$result = $posts->updateone (
["_id" => new Mongodb\bson\objectid ($id)],
[' $push ' => [' comments ']
=> $new _comment_data
]
]);
Finally hope that this article is helpful to everyone. Thank you for your support to this site!