Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

MongoDB Databases & Collections

Databases in MongoDB

A MongoDB server can host multiple databases. Each database has its own set of collections and is isolated from others. MongoDB creates a database automatically the first time you insert data into it — there is no explicit CREATE DATABASE command needed.

Managing Databases
// List all databases (only shows databases with data)
show dbs

// Switch to a database (creates it on first write)
use myapp

// Show current database name
db

// Get database statistics
db.stats()

// Drop the current database (irreversible!)
db.dropDatabase()

// Copy a database (deprecated in newer versions — use mongodump/mongorestore)
// db.copyDatabase("source", "destination")

Collections in MongoDB

Collections are analogous to tables in relational databases. They hold groups of documents. Collections are created implicitly when you first insert a document, or explicitly using createCollection() when you need to set specific options like capped collections or validation rules.

Creating and Managing Collections
use myapp

// Implicit creation — collection is created on first insert
db.users.insertOne({ name: "Alice" })

// Explicit creation with options
db.createCollection("products")

// List all collections in current database
show collections
// or
db.getCollectionNames()

// Get collection info (includes options and UUID)
db.getCollectionInfos({ name: "users" })

// Rename a collection
db.users.renameCollection("customers")

// Drop a collection (removes all documents and indexes)
db.products.drop()

// Get collection statistics
db.users.stats()
db.users.totalSize()
db.users.storageSize()

Capped Collections

Capped collections are fixed-size collections that automatically overwrite the oldest documents when the size limit is reached. They are ideal for logs, caches, and event streams where you only need the most recent data.

Capped Collections and Collection Options
// Create a capped collection
// size: max bytes (required), max: max number of documents (optional)
db.createCollection("appLogs", {
  capped: true,
  size: 10485760,   // 10 MB
  max: 5000         // max 5000 documents
})

// Check if a collection is capped
db.appLogs.isCapped()   // true

// Create a collection with a collation (language-specific sorting)
db.createCollection("articles", {
  collation: { locale: "en", strength: 2 }
})

// Convert an existing collection to capped
db.runCommand({
  convertToCapped: "logs",
  size: 5242880   // 5 MB
})

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.