- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }Advertisements