How to work with variables in MongoDB query


To use variables, work with var in MongoDB. Let us create a collection with documents −

> db.demo107.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2ee1b19fd5fd66da214471")
}
> db.demo107.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2ee1b49fd5fd66da214472")
}
> db.demo107.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2ee1b89fd5fd66da214473")
}

Display all documents from a collection with the help of find() method −

> db.demo107.find();

This will produce the following output −

{ "_id" : ObjectId("5e2ee1b19fd5fd66da214471"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2ee1b49fd5fd66da214472"), "Name" : "Bob" }
{ "_id" : ObjectId("5e2ee1b89fd5fd66da214473"), "Name" : "David" }

Following is the query to use variable in MongoDB −

> var firstName="Bob";
> db.demo107.find({"Name":firstName});

This will produce the following output −

{ "_id" : ObjectId("5e2ee1b49fd5fd66da214472"), "Name" : "Bob" }

Updated on: 30-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements