Để lưu trữ kết quả truy vấn (một tài liệu duy nhất) vào một biến, bạn có thể sử dụng var. Sau đây là cú pháp
var anyVariableName=db.yourCollectionName.find().limit(1); yourVariableName; //Print the records;
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.storeQueryResultDemo.insertOne({"ClientName":"Chris","ClientAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ecf8fd628fa4220163b8d")
}
> db.storeQueryResultDemo.insertOne({"ClientName":"Robert","ClientAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ecf97d628fa4220163b8e")
}
> db.storeQueryResultDemo.insertOne({"ClientName":"Sam","ClientAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ecf9ed628fa4220163b8f")
}
> db.storeQueryResultDemo.insertOne({"ClientName":"Mike","ClientAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ecfa8d628fa4220163b90")
} 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.storeQueryResultDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9ecf8fd628fa4220163b8d"),
"ClientName" : "Chris",
"ClientAge" : 23
}
{
"_id" : ObjectId("5c9ecf97d628fa4220163b8e"),
"ClientName" : "Robert",
"ClientAge" : 21
}
{
"_id" : ObjectId("5c9ecf9ed628fa4220163b8f"),
"ClientName" : "Sam",
"ClientAge" : 25
}
{
"_id" : ObjectId("5c9ecfa8d628fa4220163b90"),
"ClientName" : "Mike",
"ClientAge" : 26
} Sau đây là truy vấn để lưu trữ kết quả truy vấn (một tài liệu duy nhất) vào một biến
> var queryResult=db.storeQueryResultDemo.find().limit(1);
Sau đây là truy vấn để hiển thị các bản ghi của biến trên
> queryResult;
Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5c9ecf8fd628fa4220163b8d"), "ClientName" : "Chris", "ClientAge" : 23 }