Selecting database inside the JS in MongoDB?

To select a database inside JavaScript in MongoDB, use the getSiblingDB() method with the var keyword to create a reference to another database from the current connection.

Syntax

var variableName = db.getSiblingDB('databaseName');

Example

Let's select a database named 'sample' using getSiblingDB() ?

selectedDatabase = db.getSiblingDB('sample');
sample

Working with the Selected Database

Now insert some documents into the selected database. Let's use a collection named 'selectDatabaseDemo' ?

selectedDatabase.selectDatabaseDemo.insertMany([
    {"ClientName": "John Smith", "ClientAge": 23},
    {"ClientName": "Carol Taylor", "ClientAge": 24}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cda794b5667f1cce01d55ad"),
        ObjectId("5cda79565667f1cce01d55ae")
    ]
}

Display all documents from the collection using find() ?

selectedDatabase.selectDatabaseDemo.find().pretty();
{
    "_id": ObjectId("5cda794b5667f1cce01d55ad"),
    "ClientName": "John Smith",
    "ClientAge": 23
}
{
    "_id": ObjectId("5cda79565667f1cce01d55ae"),
    "ClientName": "Carol Taylor",
    "ClientAge": 24
}

Key Points

  • getSiblingDB() creates a reference to another database without switching the current context.
  • The variable stores the database reference for performing operations on the selected database.
  • All collection operations can be performed using the variable followed by collection name.

Conclusion

The getSiblingDB() method provides an efficient way to work with multiple databases within the same MongoDB connection. Store the database reference in a variable to perform operations without switching contexts.

Updated on: 2026-03-15T01:02:46+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements