Working with Databases and Collections

1. Creating Database

ActionCommandNotes
Switch / lazy createuse mydbDB exists only after first write
Explicit (via insert)db.users.insertOne({})Creates DB + collection
From driverclient.db("mydb")Lazy reference

2. Listing Databases

CommandOutput
show dbsmongosh helper, lists with size
db.adminCommand({listDatabases: 1})Full info
db.getMongo().getDBNames()Names only
listDatabases.filterFilter by criteria

3. Dropping Database

CommandEffect
use mydb; db.dropDatabase()Removes DB + all collections
db.adminCommand({dropDatabase: 1})Same, explicit
Warning: Irreversible. Confirm with db.getName() first.

4. Creating Collection

ApproachCommand
Implicitdb.users.insertOne({})
Explicitdb.createCollection("users")
With validatordb.createCollection("users", { validator: {...} })
Cappeddb.createCollection("logs", { capped: true, size: 1048576 })
Time seriesdb.createCollection("m", { timeseries: { timeField: "ts" } })

5. Listing Collections

CommandOutput
show collectionsNames list
db.getCollectionNames()Array of names
db.getCollectionInfos()Full info: type, options, idIndex
db.runCommand({listCollections: 1})Raw cursor

6. Dropping Collection

CommandEffect
db.users.drop()Removes collection + indexes
db.users.deleteMany({})Removes docs only, keeps indexes

7. Renaming Collection

OptionDescription
db.users.renameCollection("members")Same DB
db.adminCommand({renameCollection: "a.x", to: "b.y"})Cross-DB (admin auth)
dropTarget: trueReplace existing target

8. Getting Collection Stats

FieldMeaning
countDocument count
sizeUncompressed bytes
storageSizeOn-disk size
avgObjSizeAverage doc size
nindexesIndex count
totalIndexSizeIndex bytes
db.users.stats({ scale: 1024 * 1024 });  // sizes in MB

9. Creating Capped Collection

OptionRequiredDescription
capped: trueyesMarks as capped
sizeyesMax bytes
maxnoMax document count
db.createCollection("auditLog", { capped: true, size: 10485760, max: 5000 });

10. Validating Collection

OptionEffect
{validate: "users"}Basic structural check
full: trueDeep scan including indexes (slow)
background: trueRun without exclusive lock (7.0+)
repair: trueAttempt to fix corruption

11. Understanding Collection Options

OptionPurpose
validatorSchema validation expression
validationLevelstrict | moderate | off
validationActionerror | warn
collationDefault collation
writeConcernDefault write concern
storageEnginePer-engine options
expireAfterSecondsTTL (time series only)

12. Using Namespace Limits

LimitValue
Namespace length (db.coll)255 bytes
DB name length64 chars
Collection name length≤255 chars (incl. db prefix)
Forbidden chars (DB)/\." $
Indexes per collection64
Index name length127 bytes