MongoDB Quick Reference
Everything you need day‑to‑day – queries, aggregation, indexes, and administration.
Core Concepts
Terminology
- Database – container for collections
- Collection – group of documents (like a table)
- Document – record (BSON – binary JSON)
- Field – key‑value pair
- Index – improves query performance
- Replica Set – primary + secondary nodes (HA)
- Sharding – horizontal scaling across clusters
- Aggregation – data processing pipeline
- ObjectId – default unique identifier (12 bytes)
Installation
- MongoDB Community – free, open‑source
- MongoDB Atlas – cloud database (free tier)
- Install:
brew install mongodb-community(Mac) - Start:
brew services start mongodb-community - Connect:
mongosh(MongoDB Shell) - URL:
mongodb://localhost:27017
Database & Collection Commands
// Show databases show dbs // Use (create) database use mydb // Show current database db // Show collections show collections // Create collection (explicit) db.createCollection("users") // Drop collection db.users.drop() // Drop database db.dropDatabase()
CRUD Operations
Create (Insert)
// Insert one document db.users.insertOne({ name: "Alice", age: 25, email: "alice@example.com", city: "Delhi" }) // Insert many db.users.insertMany([ { name: "Bob", age: 30, email: "bob@example.com" }, { name: "Charlie", age: 35, email: "charlie@example.com" } ]) // Insert with explicit _id db.users.insertOne({ _id: 1, name: "Alice" })
Read (Find)
// Find all db.users.find() // Pretty print db.users.find().pretty() // Find with filter db.users.find({ age: 25 }) db.users.find({ age: { $gt: 25 } }) // Projection (select fields) db.users.find({}, { name: 1, age: 1, _id: 0 }) // Limit / Skip / Sort db.users.find().limit(5).skip(10).sort({ age: -1 }) // Find one db.users.findOne({ name: "Alice" })
Update
// Update one db.users.updateOne( { name: "Alice" }, { $set: { age: 26 } } ) // Update many db.users.updateMany( { city: "Delhi" }, { $set: { country: "India" } } ) // Replace (full document) db.users.replaceOne( { name: "Alice" }, { name: "Alice", age: 26, city: "Mumbai" } ) // Increment db.users.updateOne( { name: "Alice" }, { $inc: { age: 1 } } ) // Push to array db.users.updateOne( { name: "Alice" }, { $push: { hobbies: "reading" } } )
Delete
// Delete one db.users.deleteOne({ name: "Alice" }) // Delete many db.users.deleteMany({ age: { $lt: 18 } })
Query Operators
| Operator | Description | Example |
|---|---|---|
$eq |
Equal | { age: { $eq: 25 } } |
$gt |
Greater than | { age: { $gt: 25 } } |
$gte |
Greater or equal | { age: { $gte: 25 } } |
$lt |
Less than | { age: { $lt: 25 } } |
$lte |
Less or equal | { age: { $lte: 25 } } |
$ne |
Not equal | { age: { $ne: 25 } } |
$in |
In array | { age: { $in: [25, 30, 35] } } |
$nin |
Not in array | { age: { $nin: [25, 30] } } |
$regex |
Pattern matching | { name: { $regex: "Ali" } } |
$exists |
Field exists | { email: { $exists: true } } |
$type |
Field type | { age: { $type: "int" } } |
$and |
Logical AND | { $and: [ { age: 25 }, { city: "Delhi" } ] } |
$or |
Logical OR | { $or: [ { age: 25 }, { city: "Delhi" } ] } |
$not |
Negation | { age: { $not: { $gt: 25 } } } |
Aggregation Pipeline
Stages
// $match – filter db.users.aggregate([ { $match: { age: { $gt: 25 } } } ]) // $group – group by db.users.aggregate([ { $group: { _id: "$city", count: { $sum: 1 } } } ]) // $project – transform fields db.users.aggregate([ { $project: { name: 1, age: 1, _id: 0 } } ]) // $sort – sort db.users.aggregate([ { $sort: { age: -1 } } ]) // $limit / $skip db.users.aggregate([ { $skip: 10 }, { $limit: 5 } ]) // $unwind – flatten array db.users.aggregate([ { $unwind: "$hobbies" } ]) // $lookup – join (similar to SQL join) db.orders.aggregate([ { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } } ])
Aggregation Operators
// $sum, $avg, $min, $max, $first, $last db.users.aggregate([ { $group: { _id: "$city", avgAge: { $avg: "$age" } } } ]) // $addFields – add computed fields db.users.aggregate([ { $addFields: { ageCategory: { $cond: { if: { $gte: ["$age", 18] }, then: "Adult", else: "Minor" } } } } ]) // $bucket – group into buckets db.users.aggregate([ { $bucket: { groupBy: "$age", boundaries: [0, 18, 30, 60], default: "Other", output: { count: { $sum: 1 } } } } ])
Indexes
// Create single field index db.users.createIndex({ email: 1 }) // Create unique index db.users.createIndex({ email: 1 }, { unique: true }) // Create compound index db.users.createIndex({ city: 1, age: -1 }) // Create text index (search) db.users.createIndex({ name: "text" }) // Create geospatial index db.places.createIndex({ location: "2dsphere" }) // List indexes db.users.getIndexes() // Drop index db.users.dropIndex("email_1")
Index Types
- Single Field – simple field
- Compound – multiple fields (order matters)
- Unique – prevents duplicates
- Text – full‑text search
- Geospatial – location queries
- TTL – time‑to‑live (expires documents)
- Sparse – only indexes documents with the field
- Partial – filters documents based on a condition
Index Performance
- Explain plan:
db.users.find({ age: 25 }).explain("executionStats") - Use covered queries – when all fields are in the index.
- Avoid unnecessary indexes – they slow down writes.
- Use compound indexes – order: equality → sort → range.
Replication (Replica Sets)
- Primary – accepts writes
- Secondary – replicates from primary (read‑only)
- Arbiter – votes for elections (no data)
- Automatic failover – if primary fails, a secondary becomes primary
// Initiate replica set rs.initiate() // Add secondary rs.add("hostname:27017") // Check status rs.status() // Connect to replica set mongosh "mongodb://primary:27017,secondary:27017/?replicaSet=myReplica"
Sharding
- Shard – each shard holds a subset of data
- Shard Key – field used to distribute data
- Config Server – stores metadata
- Mongos – router that directs queries to appropriate shards
// Enable sharding on database sh.enableSharding("mydb") // Shard a collection sh.shardCollection("mydb.users", { _id: "hashed" }) // Add shard sh.addShard("shard1/localhost:27018")
Mongoose (Node.js ODM)
Setup
const mongoose = require('mongoose');
// Connect
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, min: 0, max: 120 },
email: { type: String, unique: true },
city: String,
hobbies: [String]
}, { timestamps: true });
// Model
const User = mongoose.model('User', userSchema);
CRUD with Mongoose
// Create const user = new User({ name: "Alice", age: 25, email: "alice@example.com" }); await user.save(); // Find const users = await User.find({ age: { $gt: 25 } }); const user = await User.findOne({ name: "Alice" }); // Update await User.updateOne({ name: "Alice" }, { $set: { age: 26 } }); // Delete await User.deleteOne({ name: "Alice" }); // Aggregation const result = await User.aggregate([ { $group: { _id: "$city", count: { $sum: 1 } } } ]); // Virtuals userSchema.virtual('ageCategory').get(function() { return this.age >= 18 ? 'Adult' : 'Minor'; });
Mongoose Indexes
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ city: 1, age: -1 });
Backup & Restore
// Backup (mongodump) mongodump --db mydb --out ./backup // Restore (mongorestore) mongorestore --db mydb ./backup/mydb // Backup (compressed) mongodump --archive=backup.gz --gzip // Restore (compressed) mongorestore --archive=backup.gz --gzip
Performance & Best Practices
- Create indexes – on frequently queried fields.
- Use covered queries – when possible.
- Avoid large documents – keep documents under 16MB.
- Use embedding – for one‑to‑one or one‑to‑many relationships when data is accessed together.
- Use referencing – for many‑to‑many or when data is accessed separately.
- Use
$lookup– sparingly (can be expensive). - Use connection pooling – in your application.
- Enable authentication – for production.
- Use replica sets – for high availability.
- Monitor with Atlas or Ops Manager – for performance.
- Use
explain()– to analyse query performance. - Use
bulkWrite– for batch operations.
📌 Quick Reference
Database:
CRUD:
Query operators:
Aggregation:
Indexes:
Replication:
Mongoose: Schema, Model,
Backup:
use db, show dbs, db.dropDatabase()CRUD:
insertOne, find, updateOne, deleteOneQuery operators:
$eq, $gt, $lt, $in, $regex, $and, $orAggregation:
$match, $group, $project, $sort, $lookup, $unwindIndexes:
createIndex, getIndexes, dropIndexReplication:
rs.initiate(), rs.status()Mongoose: Schema, Model,
find, save, updateOne, deleteOneBackup:
mongodump, mongorestore