Để truy xuất tài liệu đầu tiên trong bộ sưu tập, bạn có thể sử dụng findOne (). Sau đây là cú pháp
var anyVariableName=db.yourCollectionName.findOne(); //To print result at MongoDB console write the variable name yourVariableName
Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Robert","ClientAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2325966324ffac2a7dc6d")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Chris","ClientAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2326266324ffac2a7dc6e")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Larry","ClientAge":29});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2326a66324ffac2a7dc6f")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"David","ClientAge":39});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2327566324ffac2a7dc70")
} 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.retrieveFirstDocumentDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5ca2325966324ffac2a7dc6d"),
"ClientName" : "Robert",
"ClientAge" : 23
}
{
"_id" : ObjectId("5ca2326266324ffac2a7dc6e"),
"ClientName" : "Chris",
"ClientAge" : 26
}
{
"_id" : ObjectId("5ca2326a66324ffac2a7dc6f"),
"ClientName" : "Larry",
"ClientAge" : 29
}
{
"_id" : ObjectId("5ca2327566324ffac2a7dc70"),
"ClientName" : "David",
"ClientAge" : 39
} Sau đây là truy vấn để truy xuất tài liệu đầu tiên trong một bộ sưu tập
> var firstDocumentOnly=db.retrieveFirstDocumentDemo.findOne(); > firstDocumentOnly;
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5ca2325966324ffac2a7dc6d"),
"ClientName" : "Robert",
"ClientAge" : 23
}