How to work with variables in MongoDB query

To use variables in MongoDB queries, work with the var keyword to declare variables and reference them in your queries. This approach makes queries more flexible and reusable.

Syntax

var variableName = "value";
db.collection.find({"field": variableName});

Sample Data

Let us create a collection with documents ?

db.demo107.insertMany([
    {"Name": "Chris"},
    {"Name": "Bob"},
    {"Name": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2ee1b19fd5fd66da214471"),
        ObjectId("5e2ee1b49fd5fd66da214472"),
        ObjectId("5e2ee1b89fd5fd66da214473")
    ]
}

Display all documents from the collection ?

db.demo107.find();
{ "_id": ObjectId("5e2ee1b19fd5fd66da214471"), "Name": "Chris" }
{ "_id": ObjectId("5e2ee1b49fd5fd66da214472"), "Name": "Bob" }
{ "_id": ObjectId("5e2ee1b89fd5fd66da214473"), "Name": "David" }

Example: Using Variable in Query

Following is the query to use variable in MongoDB ?

var firstName = "Bob";
db.demo107.find({"Name": firstName});
{ "_id": ObjectId("5e2ee1b49fd5fd66da214472"), "Name": "Bob" }

Key Points

  • Variables are declared using var keyword followed by variable name and value
  • Variables can store strings, numbers, objects, or arrays for use in queries
  • This approach is particularly useful for complex queries and script automation

Conclusion

MongoDB variables using var make queries more dynamic and reusable. Simply declare the variable with var and reference it directly in your query conditions.

Updated on: 2026-03-15T01:55:45+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements