How to define aliases in the MongoDB Shell?

To define aliases in the MongoDB shell, you can create shortcuts for frequently used functions or expressions using Object.defineProperty(). This allows you to create reusable commands with custom names.

Syntax

Object.defineProperty(this, 'yourFunctionName', {
   get: function() {
      // your statements here
      return someValue;
   },
   enumerable: true,
   configurable: true
});

To assign the alias to a variable:

var anyAliasName = yourFunctionName;

Example

Let's create an alias called displayMessageDemo that returns a greeting message:

Object.defineProperty(this, 'displayMessageDemo', {
   get: function() {
      return "Hello MongoDB";
   },
   enumerable: true,
   configurable: true
});

Now assign the function to a variable:

var myMessage = displayMessageDemo;

Display the value of the alias:

myMessage;
Hello MongoDB

Key Points

  • enumerable: true makes the property visible in object enumerations
  • configurable: true allows the property to be modified or deleted later
  • The get function is called whenever the alias is accessed

Conclusion

MongoDB shell aliases using Object.defineProperty() provide a convenient way to create custom shortcuts for complex operations. This improves productivity by reducing repetitive typing of common commands.

Updated on: 2026-03-15T01:09:19+05:30

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements