
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
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" }
- Related Questions & Answers
- How to work Date query with ISODate in MongoDB?
- How to work with Stored JavaScript in MongoDB?
- Work with $push in MongoDB
- How to query MongoDB with a LIMIT?
- How to query with nand operator in MongoDB?
- What are bind variables? How to execute a query with bind variables using JDBC?
- How to query MongoDB with “like”?
- How static variables in member functions work in C++?
- How to query MongoDB a value with $lte and $in?
- How to update many documents with one query in MongoDB?
- Query MongoDB with length criteria?
- Create array with MongoDB query?
- Query MongoDB collection starting with _?
- How do I work with array fields in MongoDB to match all?
- MongoDB query with $all in array
Advertisements