- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
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
Variable collection name in MongoDB shell with JavaScript?
Yes, you can set a variable collection name in MongoDB shell using JavaScript. Let us first create a collection with documents −
> db.employeeInformation.insertOne({"EmployeeName":"John Smith","EmployeeAge":24,"EmployeeSalary":450000}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6d06baf8e7a4ca6b2ad97") }
Following is the query to display all documents from a collection with the help of find() method −
> db.employeeInformation.find();
This will produce the following output −
{ "_id" : ObjectId("5cc6d06baf8e7a4ca6b2ad97"), "EmployeeName" : "John Smith", "EmployeeAge" : 24, "EmployeeSalary" : 450000 }
Here is the query to set variable collection name in MongoDB shell using JavaScript.
Case 1 − Set variable with var
The query is as follows −
> var status=db.employeeInformation; > status.find();
This will produce the following output −
{ "_id" : ObjectId("5cc6d06baf8e7a4ca6b2ad97"), "EmployeeName" : "John Smith", "EmployeeAge" : 24, "EmployeeSalary" : 450000 }
Case 2 − We have assigned another variable collection name in MongoDB with var. The query is as follows −
> var employeeDetails=db.employeeInformation; > employeeDetails.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc6d06baf8e7a4ca6b2ad97"), "EmployeeName" : "John Smith", "EmployeeAge" : 24, "EmployeeSalary" : 450000 }
- Related Articles
- How to unset a variable in MongoDB shell?
- Deleting all records of a collection in MongoDB Shell?
- Change collection name in MongoDB?
- Renaming column name in a MongoDB collection?
- How can I drop a collection in MongoDB with two dashes in the name?
- Can we use the “.” symbol in MongoDB collection name?
- Update MongoDB variable value with variable itself?
- Query MongoDB collection starting with _?
- Find the MongoDB collection size for name “Chris”
- Is it possible to use variable for collection name using PyMongo?
- MongoDB concurrent update with sub collection?
- Prettyprint in MongoDB shell as default?
- Format date value in MongoDB shell?
- Push query results into variable with MongoDB?
- Nested collection filter with JavaScript

Advertisements