MongoDB Database Management

Contents

Introduction to MongoDB

MongoDB is a document-oriented NoSQL database that provides high performance, high availability, and easy scalability. It stores data in flexible, JSON-like documents.

Key Features:

  • Document-oriented storage
  • High scalability
  • Rich query language
  • High availability with replica sets
  • Horizontal scaling with sharding
  • Support for ad hoc queries

Why MongoDB?

  • Flexible schema design
  • Handles large volumes of unstructured data
  • Native scaling capabilities
  • Rich ecosystem and tooling
  • Strong community support

Installation and Setup

Installation Steps

# Ubuntu/Debian wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add - echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list sudo apt update sudo apt install -y mongodb-org # Start MongoDB sudo systemctl start mongod sudo systemctl enable mongod # Verify installation mongosh

Basic Configuration

# mongod.conf storage: dbPath: /var/lib/mongodb systemLog: destination: file path: /var/log/mongodb/mongod.log net: port: 27017 bindIp: 127.0.0.1 security: authorization: enabled

CRUD Operations

Create Operations

// Insert a single document db.users.insertOne({ name: "John Doe", email: "john@example.com", age: 30 }); // Insert multiple documents db.users.insertMany([ { name: "Jane Smith", email: "jane@example.com" }, { name: "Bob Johnson", email: "bob@example.com" } ]);

Read Operations

// Find documents db.users.find({ age: { $gt: 25 } }); // Find one document db.users.findOne({ email: "john@example.com" }); // Query with projection db.users.find( { age: { $gt: 25 } }, { name: 1, email: 1, _id: 0 } );

Update Operations

// Update one document db.users.updateOne( { email: "john@example.com" }, { $set: { age: 31 } } ); // Update multiple documents db.users.updateMany( { age: { $lt: 30 } }, { $inc: { age: 1 } } );

Delete Operations

// Delete one document db.users.deleteOne({ email: "john@example.com" }); // Delete multiple documents db.users.deleteMany({ age: { $lt: 18 } });

Data Modeling

Document Structure

// Embedded Documents db.orders.insertOne({ orderId: "12345", customer: { name: "John Doe", email: "john@example.com", address: { street: "123 Main St", city: "Boston", state: "MA" } }, items: [ { product: "Laptop", price: 999.99, quantity: 1 }, { product: "Mouse", price: 24.99, quantity: 2 } ] });

References

// Referenced Documents db.products.insertOne({ _id: ObjectId("..."), name: "Laptop", price: 999.99 }); db.orders.insertOne({ customer_id: ObjectId("..."), product_ids: [ObjectId("...")] }); // Lookup referenced documents db.orders.aggregate([ { $lookup: { from: "products", localField: "product_ids", foreignField: "_id", as: "products" } } ]);

Aggregation Framework

Pipeline Stages

// Basic aggregation db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$customer_id", total: { $sum: "$total" }, count: { $sum: 1 } }}, { $sort: { total: -1 } } ]); // Complex aggregation db.sales.aggregate([ { $match: { date: { $gte: ISODate("2025-01-01"), $lt: ISODate("2026-01-01") } } }, { $group: { _id: { month: { $month: "$date" }, year: { $year: "$date" } }, totalSales: { $sum: "$amount" }, avgSale: { $avg: "$amount" } } }, { $sort: { "_id.year": 1, "_id.month": 1 } } ]);

Indexing and Performance

Index Types

// Single field index db.users.createIndex({ email: 1 }); // Compound index db.products.createIndex({ category: 1, name: 1 }); // Text index db.articles.createIndex({ content: "text", title: "text" }); // Geospatial index db.locations.createIndex({ coordinates: "2dsphere" });

Query Optimization

// Explain query plan db.users.find({ age: { $gt: 25 } }).explain("executionStats"); // Index usage stats db.collection.aggregate([ { $indexStats: {} } ]);

Database Administration

User Management

// Create user db.createUser({ user: "appUser", pwd: "secure123", roles: [ { role: "readWrite", db: "myapp" }, { role: "read", db: "reporting" } ] }); // Grant roles db.grantRolesToUser("appUser", [ { role: "dbAdmin", db: "myapp" } ]);

Backup and Recovery

# Create backup mongodump --db=myapp --out=/backup/ # Restore backup mongorestore --db=myapp /backup/myapp/ # Point-in-time recovery mongodump --db=myapp --oplog mongorestore --oplogReplay

Best Practices

Schema Design

  • Design for most frequent queries
  • Consider document growth
  • Limit array sizes
  • Use appropriate data types
  • Balance embedding vs referencing

Performance

  • Create proper indexes
  • Monitor query performance
  • Use appropriate write concern
  • Consider data lifecycle management
  • Implement proper backup strategy