Variable collection name in MongoDB shell with JavaScript?

Yes, you can set a variable collection name in MongoDB shell using JavaScript. This allows you to reference collections through variables instead of typing the full collection name repeatedly.

Syntax

var variableName = db.collectionName;
variableName.find();

Sample Data

Let us first create a collection with documents ?

db.employeeInformation.insertOne({
    "EmployeeName": "John Smith",
    "EmployeeAge": 24,
    "EmployeeSalary": 450000
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cc6d06baf8e7a4ca6b2ad97")
}

Display all documents from the collection ?

db.employeeInformation.find();
{ "_id": ObjectId("5cc6d06baf8e7a4ca6b2ad97"), "EmployeeName": "John Smith", "EmployeeAge": 24, "EmployeeSalary": 450000 }

Method 1: Using Short Variable Names

Set a short variable name for the collection ?

var status = db.employeeInformation;
status.find();
{ "_id": ObjectId("5cc6d06baf8e7a4ca6b2ad97"), "EmployeeName": "John Smith", "EmployeeAge": 24, "EmployeeSalary": 450000 }

Method 2: Using Descriptive Variable Names

Use a more descriptive variable name for better readability ?

var employeeDetails = db.employeeInformation;
employeeDetails.find().pretty();
{
    "_id": ObjectId("5cc6d06baf8e7a4ca6b2ad97"),
    "EmployeeName": "John Smith",
    "EmployeeAge": 24,
    "EmployeeSalary": 450000
}

Key Points

  • Variables store references to collections, making code more readable and reusable.
  • All collection methods work with variable references (find, insert, update, etc.).
  • Use descriptive variable names for better code maintainability.

Conclusion

Setting variable collection names in MongoDB shell improves code readability and reduces typing. Simply assign db.collectionName to a variable and use it for all collection operations.

Updated on: 2026-03-15T00:55:02+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements