Variable collection name in MongoDB shell with JavaScript?

MongoDBDatabaseBig Data Analytics

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
}
raja
Published on 21-May-2019 08:54:21
Advertisements