[MongoDB] Connecting to Another DB from mongo shell to Execute Queries

Tadashi Shigeoka ·  Sat, January 24, 2015

I’ll introduce how to connect to another database and execute queries in MongoDB.

MongoDB | モンゴディービー

Prerequisites

Let’s assume we’re managing collections separately across two DB servers.

Database 1

  • Host: mongodb1
  • Port: 27017
  • DB: myDb

Database 2

  • Host: mongodb2
  • Port: 27017
  • DB: myDb

How to Create a Connection to Another DB

When you want to handle collections from another DB while executing queries in mongo shell, you can create a connection to that DB.

$ mongo mongodb1/myDb
mongodb1> db2 = connect("mongodb2:27017/myDb")
connecting to: mongodb2:27017/myDb
myDb

// You can now handle data from somecollections saved in myDb on mongodb2 server
mongodb1> db2.somecollections.findOne()

When there was only one DB server, I didn’t need to worry about this, but with multiple servers, knowing tips for handling connections to different DB servers lets you keep executing queries from mongo shell as usual.

Reference Information

That’s all from the Gemba.