Database-level management operations, including listing databases, deleting databases, listing collections, etc.
List all databases on the MongoDB server.
const databases = await db.listDatabases(options);- options (Object, optional):
nameOnly(boolean): only returns the database name, defaultfalse
- Do not use nameOnly:
Promise<Array<Object>>name(string): database namesizeOnDisk(number): Disk usage (bytes)empty(boolean): whether it is empty
- Use nameOnly:
Promise<Array<string>>
//Get details
const databases = await db.listDatabases();
console.log(databases);
// [
// { name: 'admin', sizeOnDisk: 83886080, empty: false },
// { name: 'mydb', sizeOnDisk: 167772160, empty: false }
// ]
//Get name only
const dbNames = await db.listDatabases({ nameOnly: true });
console.log(dbNames); // ['admin', 'config', 'local', 'mydb']- Must be explicitly confirmed:
{ confirm: true }must be passed in - Production environment protection:
NODE_ENV=production,prod, orliveis blocked by default and requires{ allowProduction: true } - Audit Log: All deletion attempts will be logged
const result = await db.db(databaseName).dropDatabase(options);- databaseName (string, required): database name
- options (Object, required):
confirm(boolean, required): must betrueallowProduction(boolean): Whether to allow execution in the production environment, defaultfalseuser(string): operating user (for auditing)
- Type:
Promise<Object> - Properties:
dropped(boolean): Whether the deletion was successfuldatabase(string): deleted database nametimestamp(Date): deletion time
try {
await db.db('test_db').dropDatabase({ confirm: false });
} catch (error) {
console.error(error.message);
// "dropDatabase requires explicit confirmation..."
}const result = await db.db('test_db').dropDatabase({
confirm: true,
user: 'admin@example.com'
});
console.log('Database dropped:', result.database);
console.log('Timestamp:', result.timestamp);// In a production-like environment (NODE_ENV=production, prod, or live)
const result = await db.db('prod_db').dropDatabase({
confirm: true,
allowProduction: true,
user: 'admin@example.com'
});try {
await db.db('my_database').dropDatabase({
confirm: true,
user: 'admin@example.com'
});
} catch (error) {
if (error.code === 'CONFIRMATION_REQUIRED') {
console.error('❌ Missing confirmation parameters');
} else if (error.code === 'PRODUCTION_BLOCKED') {
console.error('❌ Production environment blocked');
} else {
console.error('❌ Delete failed:', error.message);
}
}List all collections in the current database.
const collections = await db.listCollections(filter, options);- filter (Object, optional): MongoDB collection-list filter
- options (Object, optional): MongoDB listCollections options
Promise<Array<Object>>
//Get details
const collections = await db.listCollections();
console.log(collections);
// [
// { name: 'users', type: 'collection', options: {}, info: {...} },
// { name: 'orders', type: 'collection', options: {}, info: {...} }
// ]
//Get name only from the public return value
const names = collections.map((collection) => collection.name);
console.log(names); // ['users', 'orders', 'products']Execute any MongoDB command.
const result = await db.runCommand(command, options);- command (Object, required): MongoDB command object
- options (Object, optional): command options
//Execute ping command
const ping = await db.runCommand({ ping: 1 });
console.log(ping.ok); // 1
//Execute dbStats command
const stats = await db.runCommand({ dbStats: 1, scale: 1024 });
console.log('Collections:', stats.collections);
console.log('Data size (KB):', stats.dataSize);
//Execute collStats command
const collStats = await db.runCommand({
collStats: 'users',
scale: 1048576 // MB
});
console.log('Count:', collStats.count);
console.log('Size (MB):', collStats.size);- Operation and Maintenance Monitoring - ping, buildInfo, serverStatus, stats
- Collection Management - Collection level operations
- Collection Management Example