Để tìm tài liệu có Objectid trong MongoDB, hãy sử dụng cú pháp sau -
db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty(); Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4384afe5c1d2279d69b")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Mike","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4444afe5c1d2279d69c")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Carol","UserAge":26,"UserHobby":["Learning","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4704afe5c1d2279d69d")
} 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 (). Truy vấn như sau -
> db.findDocumentWithObjectIdDemo.find().pretty();
Sau đây là kết quả -
{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" }
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
} Trường hợp 1 - Đây là truy vấn để tìm tài liệu với ObjectId trong MongoDB.
> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty(); Sau đây là kết quả -
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
} Trường hợp 2 - Đây là truy vấn để tìm một tài liệu khác với ObjectId trong MongoDB.
Truy vấn như sau -
> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty(); Sau đây là kết quả -
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}