Home > php教程 > PHP开发 > body text

PHP library method to query document ID in Mongodb

高洛峰
Release: 2016-12-23 12:58:06
Original
1437 people have browsed it

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
      ]
]);
Copy after login

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!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template