 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to set user defined variable into query?
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" }Advertisements
 