MongoDBDatabases Deep Dive

MongoDB Databases

A MongoDB database is the top-level container in the hierarchy: a server (or cluster) holds databases, a database holds collections, and a collection holds documents. One MongoDB deployment can serve many databases, each fully isolated from the others in naming and (optionally) access control.

The MongoDB hierarchy

Text
MongoDB deployment (mongod / cluster)
└── Database        (e.g. shop)
    └── Collection  (e.g. products)
        └── Document (e.g. { name: "Keyboard", price: 79.99 })
Switching Databases with use

In mongosh, the use command switches the current database context. The db variable always refers to the current database.

Switching context

JS
use shop            // switch to (or prepare to create) the shop database
db                  // print the current database name
db.getName()        // same, as a method
switched to db shop
shop
shop
Databases Are Created Implicitly

There is no CREATE DATABASE statement in MongoDB. Running use shop does not create anything yet — the database materializes the moment you first store data in it.

Implicit creation

JS
use shop
show dbs            // "shop" is NOT listed yet — it holds no data

db.products.insertOne({ name: "Keyboard", price: 79.99 })

show dbs            // now "shop" appears
admin    40.00 KiB
config   72.00 KiB
local    80.00 KiB

{ acknowledged: true, insertedId: ObjectId("665f1a2b3c4d5e6f7a8b9c0d") }

admin    40.00 KiB
config   72.00 KiB
local    80.00 KiB
shop      8.00 KiB
Tip
Because creation is implicit, a typo like `use shpo` silently gives you a new empty database instead of an error. If a collection you expect seems empty, check `db` first — you may be in the wrong database.
Listing Databases

Ways to list databases

JS
show dbs                        // mongosh shorthand
show databases                  // identical alias

db.adminCommand({ listDatabases: 1 })          // full command form
db.adminCommand({ listDatabases: 1, nameOnly: true })  // names only (faster)
Note
`show dbs` only lists databases that contain data. An empty database you just switched to with `use` will not appear until you insert something or explicitly create a collection.
The System Databases

Every MongoDB deployment maintains a few internal databases. Treat them as read-only unless you know exactly what you are doing:

Database

Purpose

Notes

admin

Server administration and authentication

Users with cluster-wide roles are defined here; some commands only run against admin

local

Node-local data, including the replication oplog

Never replicated; do not store application data here

config

Sharded cluster metadata (chunks, shard mapping)

Managed by MongoDB in sharded deployments; also holds session data

Warning
Never store application data in `admin`, `local`, or `config`. Writing to `local` bypasses replication entirely, and modifying `config` by hand can corrupt a sharded cluster.
Database Naming Rules
  • Names are case-insensitive on Windows and case-sensitive on Linux/macOS — never rely on case to distinguish databases (Shop vs shop is asking for trouble).

  • Maximum length: 64 characters (63 bytes for some platforms).

  • Cannot be empty and cannot contain: /, \, ., double quotes, *, angle brackets, colon, pipe, question mark, dollar sign, space, or the null character.

  • Convention: short, lowercase, no spaces — shop, analytics, user_service.

Inspecting a Database

Database-level information

JS
use shop

db.stats()                 // size, object counts, index sizes
db.stats(1024 * 1024)      // same, scaled to megabytes

show collections           // list collections in the current database
db.getCollectionNames()    // same, as an array
db.getCollectionInfos()    // includes options and metadata

db.version()               // server version
db.serverStatus().uptime   // server uptime in seconds
{
  db: 'shop',
  collections: 3,
  views: 0,
  objects: 15204,
  avgObjSize: 512.4,
  dataSize: 7790649,
  storageSize: 2891776,
  indexes: 7,
  indexSize: 1105920,
  totalSize: 3997696,
  ok: 1
}
Dropping a Database

db.dropDatabase() deletes the current database — all of its collections, documents, and indexes.

Dropping a database

JS
use temp_analytics
db.dropDatabase()
{ ok: 1, dropped: 'temp_analytics' }
Warning
dropDatabase is immediate and irreversible — there is no confirmation prompt and no undo. It drops whatever database is currently selected, so always verify with the db command first. On a replica set the drop replicates to all members; your backups are the only recovery path.
Working Across Databases

You can reference another database without switching context using db.getSiblingDB() — handy in scripts where use is not available:

getSiblingDB

JS
// While "shop" is the current database:
const reporting = db.getSiblingDB("reporting")
reporting.dailyStats.insertOne({ date: new Date(), orders: 152 })

// One-liner reads from another database
db.getSiblingDB("admin").system.version.findOne()

// Loop over every database
db.adminCommand({ listDatabases: 1 }).databases.forEach(d => {
  print(d.name, "-", d.sizeOnDisk, "bytes")
})
How Many Databases Should You Have?
  • One database per application/service is the most common pattern — collections separate the entity types inside it.

  • One database per tenant works for strong multi-tenant isolation, but thousands of databases add per-database overhead; a tenant field plus indexes often scales better.

  • Separate databases for unrelated concerns (app data vs. analytics dumps) keeps permissions and backups clean.

Note
Authorization in MongoDB is commonly granted per database (e.g. the readWrite role on shop), so database boundaries are also security boundaries. Group data that shares an access-control story.
Summary
  • Databases are the top-level containers; switch between them with use and inspect the current one via db.

  • Databases are created implicitly on first write and listed with show dbs (only once they contain data).

  • admin, local, and config are system databases — never store application data in them.

  • db.dropDatabase() irreversibly deletes the current database; double-check db before running it.

  • Use db.getSiblingDB() to work across databases in scripts, and keep database boundaries aligned with your access-control needs.