6

I'm using the MongoDB shell and like to define some shortcuts. For example, it would be nice to abbreviate show databases with sd.

I already managed to add a function hw() to the MongoDB shell by adding it's definition to the ~/.mongorc.js:

function hw() {
    print("Hello World.");
}

When I type hw() in the mongo-shell, it prints out Hello World.


Question 1: Is it also possible to execute the function without having to type the brackets (i.e. hw instead of hw())?

I tried to bind the function to variable using anonymous functions, but still I have to type brackets, otherwise the definition of the function is printed out

hw=function(){ print("Hello World (anonymous)."); };

Question 2: How can I execute MongoDB commands from within my functions? I tried:

function sd() {
    show databases;
}

but that gives an error during startup of the MongoDB shell:

SyntaxError: Unexpected identifier at /home/edward/.mongorc.js:2

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Edward
  • 4,453
  • 8
  • 44
  • 82

2 Answers2

7

To list databases try :

function sd(){
     return db._adminCommand( { listDatabases: 1 } ) 
}

Basically you have to run valid javascript here. Remember that you have to run these in context of admin database - runCommand will not be enough - you have to use _adminCommand here.

For other commands see http://docs.mongodb.org/manual/reference/command/

if you would like to get rid of parenthesis there is also a way (you would have to put property on 'this')

Object.defineProperty(this, 'sd', {
    get: function() { 
        return db._adminCommand( {listDatabases: 1} )
    },
    enumerable: true,
    configurable: true
});
marcinn
  • 1,786
  • 11
  • 13
1

Another way to alias databases in the mongo shell is to use the db.getSiblingDB() command. In the following, imagine you have two MongoDB databases - AmazonSales and EbaySales. Both the databases have a users collection. You can now use the aliases as described below in the Mongo shell, instead of always needing the 'use ' command to switch context

var cs = db.getSiblingDB('AmazonSales')
cs.users.count()
cs.users.find({name:'John'})

var r = db.getSiblingDB('EbaySales')
r.users.count()
ice.nicer
  • 1,644
  • 14
  • 13