如何将查询结果(单个文档)存储到变量中?
要将查询结果(单个文档)存储在变量中,可以使用 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 }
广告