MongoDB
This MongoDB cheatsheet provides a quick
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents.
Database Basics
Show Databases
show dbs
Create or Switch Database
use myDatabase
Show Current Database
db
Collections
Show Collections
show collections
Create Collection
db.createCollection("users")
Drop Collection
db.users.drop()
CRUD Operations
Insert Documents
db.users.insertOne({ name: "Alice", age: 25, email: "alice@example.com" }) db.users.insertMany([ { name: "Bob", age: 30 }, { name: "Charlie", age: 28 } ])
Find Documents
db.users.find() db.users.find({ age: { $gt: 25 } }) db.users.findOne({ name: "Alice" })
Update Documents
db.users.updateOne( { name: "Alice" }, { $set: { age: 26 } } ) db.users.updateMany( { age: { $lt: 30 } }, { $inc: { age: 1 } } )
Delete Documents
db.users.deleteOne({ name: "Bob" }) db.users.deleteMany({ age: { $lt: 30 } })
Query Operators
- Comparison: ne, gte, lte, nin
- Logical: or, nor
- Element: type
- Evaluation: mod, where
- Array: all, slice
Example:
db.users.find({ age: { $gte: 25, $lte: 30 } })
Projection (Select Fields)
db.users.find({ age: { $gte: 25 } }, { name: 1, age: 1, _id: 0 })
Sorting
db.users.find().sort({ age: 1 }) // ascending db.users.find().sort({ age: -1 }) // descending
Limit & Skip
db.users.find().limit(5) // First 5 documents db.users.find().skip(5) // Skip first 5 documents
Indexing
Create Index
db.users.createIndex({ name: 1 }) // Ascending db.users.createIndex({ age: -1 }) // Descending
Drop Index
db.users.dropIndex("name_1")
List Indexes
db.users.getIndexes()
Aggregation
Basic Aggregation Pipeline
db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } }, { $sort: { totalAmount: -1 } } ])
Common Aggregation Operators
- group, sort, skip, lookup
Data Types
- String
- Number (int, double, long, decimal)
- Boolean
- Array
- Object
- Date
- Null
- ObjectId
- Embedded Document
Example:
db.users.insertOne({ name: "Alice", age: 25, address: { city: "NYC", zip: "10001" }, hobbies: ["reading", "gaming"], isActive: true })
User & Role Management
Create User
db.createUser({ user: "admin", pwd: "password123", roles: [ { role: "readWrite", db: "myDatabase" } ] })
Show Users
show users
Backup & Restore
- Backup: `mongodump --db myDatabase --out /backup/path`
- Restore: `mongorestore /backup/path/myDatabase`
Commands
- Show Current Operations: `db.currentOp()`
- Server Status: `db.serverStatus()`
- Database Stats: `db.stats()`
- Collection Stats: `db.users.stats()`
- Explain Query: `db.users.find({}).explain("executionStats")`
Tips
- MongoDB shell: 'mongosh'
- Default port: 27017
- NoSQL → schema-less, flexible structure
- JSON-like documents → BSON internally