Để tìm bản ghi theo _id trong MongoDB, bạn có thể sử dụng cú pháp sau
db.yourCollectionName.find({"_id":yourObjectId}); Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
> db.findRecordByIdDemo.insertOne({"CustomerName":"Larry","CustomerAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9dc2c875e2eeda1d5c3671")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"Bob","CustomerAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9dc2d175e2eeda1d5c3672")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"Carol","CustomerAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9dc2d775e2eeda1d5c3673")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"David","CustomerAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9dc2e375e2eeda1d5c3674")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.findRecordByIdDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9dc2c875e2eeda1d5c3671"),
"CustomerName" : "Larry",
"CustomerAge" : 26
}
{
"_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"),
"CustomerName" : "Bob",
"CustomerAge" : 20
}
{
"_id" : ObjectId("5c9dc2d775e2eeda1d5c3673"),
"CustomerName" : "Carol",
"CustomerAge" : 22
}
{
"_id" : ObjectId("5c9dc2e375e2eeda1d5c3674"),
"CustomerName" : "David",
"CustomerAge" : 24
}
Following is the query to find record by _id in MongoDB:
> db.findRecordByIdDemo.find({"_id":ObjectId("5c9dc2d175e2eeda1d5c3672")}).pretty(); Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"),
"CustomerName" : "Bob",
"CustomerAge" : 20
}