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

To store a query result (a single document) into a variable in MongoDB, use the var keyword with find().limit(1) to retrieve only one document. You can then access the stored result by referencing the variable name.

Syntax

var variableName = db.collectionName.find().limit(1);
variableName; // Display the stored result

Sample Data

Let us first create a collection with sample documents ?

db.storeQueryResultDemo.insertMany([
    {"ClientName": "Chris", "ClientAge": 23},
    {"ClientName": "Robert", "ClientAge": 21},
    {"ClientName": "Sam", "ClientAge": 25},
    {"ClientName": "Mike", "ClientAge": 26}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9ecf8fd628fa4220163b8d"),
        ObjectId("5c9ecf97d628fa4220163b8e"),
        ObjectId("5c9ecf9ed628fa4220163b8f"),
        ObjectId("5c9ecfa8d628fa4220163b90")
    ]
}

Example: Store Single Document in Variable

Store the first document from the collection into a variable ?

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

Display the stored result ?

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

Key Points

  • The limit(1) method ensures only one document is retrieved and stored.
  • Variables in MongoDB shell persist for the current session only.
  • You can apply additional query conditions before limit(1) to store specific documents.

Conclusion

Use var variableName = db.collection.find().limit(1) to store a single document in a variable. This approach is useful for temporary storage and manipulation of query results within the MongoDB shell session.

Updated on: 2026-03-15T00:40:50+05:30

590 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements