MongoDB query to set user defined variable into query?

MongoDBDatabaseBig Data Analytics

For user-defined variables, use var keyword in MongoDB. Let us create a collection with documents −

> db.demo327.insertOne({"FirstName":"Chris","LastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516952f8647eb59e562076")
}
> db.demo327.insertOne({"FirstName":"David","LastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e51695af8647eb59e562077")
}
> db.demo327.insertOne({"FirstName":"John","LastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516962f8647eb59e562078")
}
> db.demo327.insertOne({"FirstName":"John","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516968f8647eb59e562079")
}

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

> db.demo327.find();

This will produce the following output −

{ "_id" : ObjectId("5e516952f8647eb59e562076"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5e51695af8647eb59e562077"), "FirstName" : "David", "LastName" : "Miller" }
{ "_id" : ObjectId("5e516962f8647eb59e562078"), "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : ObjectId("5e516968f8647eb59e562079"), "FirstName" : "John", "LastName" : "Smith" }

Following is how to set a user-defined variable into the query −

> var name="John";
> db.demo327.find({"FirstName":name});

This will produce the following output −

{ "_id" : ObjectId("5e516962f8647eb59e562078"), "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : ObjectId("5e516968f8647eb59e562079"), "FirstName" : "John", "LastName" : "Smith" }
raja
Published on 02-Apr-2020 10:04:09
Advertisements