如何将查询结果(单个文档)存储到变量中?
要将查询结果(单个文档)存储到变量中,可以使用var。以下是语法
var anyVariableName=db.yourCollectionName.find().limit(1);yourVariableName; //Print the records;
首先让我们创建一个包含文档的集合
> 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")
}
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.storeQueryResultDemo.find().pretty();
这将产生以下输出
{"_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
}
以下是将查询结果(单个文档)存储到变量中的查询
> var queryResult=db.storeQueryResultDemo.find().limit(1);
以下是显示上述变量的记录的查询
> queryResult;
这将产生以下输出
{ "_id" : ObjectId("5c9ecf8fd628fa4220163b8d"), "ClientName" : "Chris", "ClientAge" : 23 }
以上是 如何将查询结果(单个文档)存储到变量中? 的全部内容, 来源链接: utcz.com/z/316676.html