Để tìm kiếm một tài liệu trong MongoDB bằng _id, bạn cần gọi ObjectId (). Đầu tiên chúng ta hãy xem cú pháp
db.yourCollectionName.find({"_id":ObjectId("yourId")}).pretty(); Để hiểu khái niệm và tìm kiếm tài liệu, chúng ta hãy triển khai truy vấn sau để tạo một bộ sưu tập với các tài liệu
> db.searchDocumentDemo.insertOne({"UserId":1,"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8e4330fd0aa0d2fe487")
}
> db.searchDocumentDemo.insertOne({"UserId":2,"UserName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8ea330fd0aa0d2fe488")
}
> db.searchDocumentDemo.insertOne({"UserId":3,"UserName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8f1330fd0aa0d2fe489")
}
> db.searchDocumentDemo.insertOne({"UserId":4,"UserName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8fa330fd0aa0d2fe48a")
}
> db.searchDocumentDemo.insertOne({"UserId":5,"UserName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a901330fd0aa0d2fe48b")
}
> db.searchDocumentDemo.insertOne({"UserId":6,"UserName":"Sam"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a911330fd0aa0d2fe48c")
} 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.searchDocumentDemo.find().pretty();
This will produce the following output:
{
"_id" : ObjectId("5c97a8e4330fd0aa0d2fe487"),
"UserId" : 1,
"UserName" : "Larry"
}
{
"_id" : ObjectId("5c97a8ea330fd0aa0d2fe488"),
"UserId" : 2,
"UserName" : "Mike"
}
{
"_id" : ObjectId("5c97a8f1330fd0aa0d2fe489"),
"UserId" : 3,
"UserName" : "David"
}
{
"_id" : ObjectId("5c97a8fa330fd0aa0d2fe48a"),
"UserId" : 4,
"UserName" : "Chris"
}
{
"_id" : ObjectId("5c97a901330fd0aa0d2fe48b"),
"UserId" : 5,
"UserName" : "Robert"
}
{
"_id" : ObjectId("5c97a911330fd0aa0d2fe48c"),
"UserId" : 6,
"UserName" : "Sam"
} Sau đây là truy vấn tìm kiếm tài liệu trong MongoDB bằng _id. Chúng tôi đã gọi ObjectId () để hiển thị kết quả:
> db.searchDocumentDemo.find({"_id":ObjectId("5c97a901330fd0aa0d2fe48b")}).pretty(); Điều này sẽ tạo ra kết quả sau:
{
"_id" : ObjectId("5c97a901330fd0aa0d2fe48b"),
"UserId" : 5,
"UserName" : "Robert"
}