How to store query result (a single document) into a variable?


To store query result (a single document) into a variable, you can use var. Following is the syntax

var anyVariableName=db.yourCollectionName.find().limit(1);
yourVariableName; //Print the records;

Let us first create a collection with documents

> 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")
}

Following is the query to display all documents from a collection with the help of find() method

> db.storeQueryResultDemo.find().pretty();

This will produce the following output

{
   "_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
}

Following is the query to store query result (a single document) into a variable

> var queryResult=db.storeQueryResultDemo.find().limit(1);

Following is the query to display records of the above variable

> queryResult;

This will produce the following output

{ "_id" : ObjectId("5c9ecf8fd628fa4220163b8d"), "ClientName" : "Chris", "ClientAge" : 23 }

Updated on: 30-Jul-2019

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements