

- 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
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" }
- Related Questions & Answers
- Push query results into variable with MongoDB?
- Perform MySQL SELECT INTO user-defined variable
- Select into a user-defined variable with MySQL
- Set user variable from result of query in MySQL?
- Add user defined value to a column in a MySQL query?
- Set user-defined variable with table name in MySQL prepare statement?
- MongoDB query to push document into an array
- MySQL ORDER BY with numeric user-defined variable?
- MongoDB query to change simple field into an object?
- MongoDB query to increment a specific value using custom variable
- C++ set for user defined data type?
- How to store query result (a single document) into a variable?
- How to set different auto-increment ids for two tables with a user-defined variable?
- A single MongoDB query to orderby date and group by user
- MongoDB query on nth element (variable index) of subdocument array
Advertisements