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
}

Updated on: 30-Jul-2019

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements