How to Switch Database in MongoDB: Simple Guide
In MongoDB shell, you switch databases using the
use <databaseName> command. In application code, you select a database by calling client.db(<databaseName>) on your MongoDB client instance.Syntax
To switch databases in the MongoDB shell, use the use command followed by the database name. In application code, use the db() method on the client object to select a database.
use <databaseName>: Switches to the specified database in the shell.client.db(<databaseName>): Returns a database object for the specified database in code.
mongodb
use myDatabase // In application code (Node.js example): const db = client.db('myDatabase');
Example
This example shows switching databases in the MongoDB shell and in Node.js code using the official MongoDB driver.
javascript
// MongoDB shell example use salesDB show collections // Node.js example import { MongoClient } from 'mongodb'; async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); // Switch to 'salesDB' database const db = client.db('salesDB'); // List collections in 'salesDB' const collections = await db.listCollections().toArray(); console.log(collections.map(c => c.name)); await client.close(); } run();
Output
[ 'orders', 'customers', 'products' ]
Common Pitfalls
Common mistakes when switching databases include:
- Using
usecommand only works in the MongoDB shell, not in application code. - Forgetting to call
client.db()to get the database object before running queries. - Assuming switching database changes the client connection; it only changes the context for commands.
javascript
// Wrong: Trying to use 'use' in Node.js code // This will cause an error client.use('salesDB'); // Right: Use client.db() method const db = client.db('salesDB');
Quick Reference
| Action | Command / Method | Context |
|---|---|---|
| Switch database in shell | use | MongoDB shell |
| Get database in code | client.db( | Application code (Node.js, Python, etc.) |
| List collections | db.getCollectionNames() or db.listCollections() | After switching database |
| Run query | db.collection.find() | On selected database |
Key Takeaways
Use
use <databaseName> in MongoDB shell to switch databases.In application code, call
client.db(<databaseName>) to select a database.Switching database does not change the connection, only the context for commands.
Do not use
use command in application code; it only works in the shell.Always get the database object before running queries on collections.