db.getSiblingDB()

Definition

  • db.getSiblingDB()

ParameterTypeDescriptiondatabasestringThe name of a MongoDB database.

Returns:A database object.

Used to return another database without modifying thedb variable in the shell environment.

Example

You can use db.getSiblingDB() as an alternative to the use<database> helper. This is particularly useful when writing scriptsusing the mongo shell where the use helper is notavailable. Consider the following sequence of operations:

  1. db = db.getSiblingDB('users')
  2. db.active.count()

This operation sets the db object to point to the database namedusers, and then returns a count of the collection namedactive. You can create multiple db objects, that refer todifferent databases, as in the following sequence of operations:

  1. users = db.getSiblingDB('users')
  2. records = db.getSiblingDB('records')
  3.  
  4. users.active.count()
  5. users.active.findOne()
  6.  
  7. records.requests.count()
  8. records.requests.findOne()

This operation creates two db objects referring to differentdatabases (i.e. users and records) and then returns acount and anexample document fromone collection in that database (i.e. active and requestsrespectively.)