Tip: A shortcut for accessing another MongoDB database from the shell

At uSwitch, I often work with multiple MongoDB databases as part of the same system. Recently I spent a lot of time in the Mongo shell jumping between the two databases to reset data to its initial state.

This requires several commands

use otherdb;
db.collectionx.remove();

use originaldb;
db.collectiony.remove();

Plus I often forget which database I’m in.

Happily you can use the db.getSiblingDB method to access another database without having to switch databases. This shorten it down to a single command:

db.getSiblingDB("otherdb").collectionx.remove();
db.getSiblingDB("originaldb").collectiony.remove();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s