📖 Guide
MongoDB — Complete Reference
MongoDB cheat sheet covering CRUD operations, query and update operators, aggregation pipeline, indexes, and administration.
91 commands across 10 categories
Database OperationsCRUDQuery OperatorsUpdate OperatorsAggregation PipelineIndexesCollection ManagementUsers & RolesReplica SetsCommon Patterns
Database Operations
| Command | Description |
|---|---|
mongosh | Open the MongoDB shell (mongosh) |
show dbs | List all databases |
use mydb | Switch to a database (creates if it doesn't exist) |
db | Show the current database name |
db.dropDatabase() | Drop the current database |
db.stats() | Get database statistics (size, collections, objects) |
db.getMongo() | Get connection info for the current session |
show collections | List all collections in the current database |
CRUD
| Command | Description |
|---|---|
db.users.insertOne({ name: 'Alice', age: 30 }) | Insert a single document |
db.users.insertMany([{ name: 'Bob' }, { name: 'Carol' }]) | Insert multiple documents |
db.users.findOne({ name: 'Alice' }) | Find the first matching document |
db.users.find({ age: { $gte: 18 } }) | Find all matching documents |
db.users.find().sort({ age: -1 }).limit(10) | Sort descending and limit results |
db.users.countDocuments({ active: true }) | Count matching documents |
db.users.updateOne({ name: 'Alice' }, { $set: { age: 31 } }) | Update the first matching document |
db.users.updateMany({ active: false }, { $set: { archived: true } }) | Update all matching documents |
db.users.replaceOne({ name: 'Alice' }, { name: 'Alice', age: 31 }) | Replace an entire document |
db.users.deleteOne({ name: 'Alice' }) | Delete the first matching document |
db.users.deleteMany({ archived: true }) | Delete all matching documents |
db.users.findOneAndUpdate({ name: 'Bob' }, { $inc: { score: 1 } }, { returnDocument: 'after' }) | Find, update, and return the modified document |
Query Operators
| Command | Description |
|---|---|
{ age: { $eq: 25 } } | Equal to (implicit with { age: 25 }) |
{ age: { $gt: 18, $lt: 65 } } | Greater than / less than |
{ status: { $in: ['active', 'pending'] } } | Match any value in array |
{ status: { $nin: ['deleted'] } } | Match none of the values in array |
{ $and: [{ age: { $gte: 18 } }, { active: true }] } | Logical AND (implicit when using multiple fields) |
{ $or: [{ age: { $lt: 18 } }, { role: 'admin' }] } | Logical OR |
{ email: { $exists: true } } | Field exists (or doesn't with false) |
{ name: { $regex: /^A/i } } | Regular expression match (case-insensitive) |
{ tags: { $all: ['js', 'node'] } } | Array contains all specified elements |
{ 'address.city': 'Vienna' } | Query nested document fields with dot notation |
Update Operators
| Command | Description |
|---|---|
{ $set: { name: 'Alice' } } | Set a field value (create if doesn't exist) |
{ $unset: { tmpField: '' } } | Remove a field from the document |
{ $inc: { count: 1 } } | Increment a numeric field |
{ $mul: { price: 1.1 } } | Multiply a numeric field |
{ $rename: { 'old': 'new' } } | Rename a field |
{ $push: { tags: 'new-tag' } } | Add an element to an array |
{ $addToSet: { tags: 'unique-tag' } } | Add to array only if not already present |
{ $pull: { tags: 'old-tag' } } | Remove matching elements from an array |
{ $pop: { tags: 1 } } | Remove last element from array (1) or first (-1) |
{ $currentDate: { updatedAt: true } } | Set field to current date |
Aggregation Pipeline
| Command | Description |
|---|---|
db.orders.aggregate([{ $match: { status: 'completed' } }]) | Filter documents (like find) |
{ $group: { _id: '$category', total: { $sum: '$amount' } } } | Group by field and calculate aggregates |
{ $sort: { total: -1 } } | Sort results (1 ascending, -1 descending) |
{ $project: { name: 1, total: 1, _id: 0 } } | Include/exclude specific fields |
{ $limit: 10 } | Limit the number of results |
{ $skip: 20 } | Skip a number of documents (pagination) |
{ $unwind: '$items' } | Deconstruct an array field into separate documents |
{ $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user' } } | Left outer join with another collection |
{ $addFields: { fullName: { $concat: ['$first', ' ', '$last'] } } } | Add computed fields to documents |
{ $count: 'totalResults' } | Count and return total number of documents |
Indexes
| Command | Description |
|---|---|
db.users.createIndex({ email: 1 }) | Create an ascending index on a field |
db.users.createIndex({ email: 1 }, { unique: true }) | Create a unique index |
db.users.createIndex({ name: 1, age: -1 }) | Create a compound index |
db.users.createIndex({ bio: 'text' }) | Create a text search index |
db.places.createIndex({ location: '2dsphere' }) | Create a geospatial index |
db.users.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 }) | TTL index — auto-delete documents after 24 hours |
db.users.getIndexes() | List all indexes on a collection |
db.users.dropIndex('email_1') | Drop an index by name |
db.users.find({ email: 'a@b.com' }).explain('executionStats') | Analyze query performance and index usage |
Collection Management
| Command | Description |
|---|---|
db.createCollection('logs', { capped: true, size: 10485760 }) | Create a capped collection (10 MB) |
db.users.drop() | Drop a collection |
db.users.renameCollection('members') | Rename a collection |
db.users.estimatedDocumentCount() | Fast approximate document count |
db.users.distinct('city') | Get unique values for a field |
db.users.find().forEach(printjson) | Iterate and print all documents |
db.users.bulkWrite([{ insertOne: { document: { name: 'X' } } }]) | Execute multiple write operations in bulk |
db.users.createIndex({ name: 1 }, { collation: { locale: 'en', strength: 2 } }) | Case-insensitive index with collation |
Users & Roles
| Command | Description |
|---|---|
db.createUser({ user: 'admin', pwd: 'pass', roles: ['root'] }) | Create a database user with a role |
db.createUser({ user: 'app', pwd: 'pass', roles: [{ role: 'readWrite', db: 'mydb' }] }) | Create a user with specific database access |
db.getUsers() | List all users in the current database |
db.updateUser('app', { roles: [{ role: 'read', db: 'mydb' }] }) | Update user roles |
db.changeUserPassword('app', 'newpass') | Change a user's password |
db.dropUser('app') | Delete a user |
db.auth('admin', 'pass') | Authenticate in the current session |
Replica Sets
| Command | Description |
|---|---|
rs.status() | Get replica set status and member states |
rs.initiate() | Initialize a new replica set |
rs.add('mongo2:27017') | Add a member to the replica set |
rs.remove('mongo2:27017') | Remove a member from the replica set |
rs.conf() | Get the replica set configuration |
rs.stepDown() | Force the primary to step down |
db.getMongo().setReadPref('secondaryPreferred') | Set read preference to secondary nodes |
mongodump --uri='mongodb://host:27017/mydb' --out=./backup | Backup a database |
mongorestore --uri='mongodb://host:27017/mydb' ./backup/mydb | Restore a database from backup |
Common Patterns
| Command | Description |
|---|---|
db.users.findOne({ _id: ObjectId('...') }) | Query by document ID |
db.users.find({}, { name: 1, email: 1, _id: 0 }) | Projection — return only specific fields |
db.users.find().sort({ createdAt: -1 }).skip(20).limit(10) | Pagination pattern |
db.orders.aggregate([{ $group: { _id: null, avg: { $avg: '$total' } } }]) | Calculate the average of a field |
db.users.updateOne({ _id: id }, { $set: data }, { upsert: true }) | Upsert — insert if not found, update if exists |
db.events.find({ date: { $gte: ISODate('2024-01-01') } }) | Query by date range |
db.products.find({ $text: { $search: 'coffee organic' } }) | Full-text search (requires text index) |
db.places.find({ loc: { $near: { $geometry: { type: 'Point', coordinates: [16.37, 48.21] } } } }) | Find documents near a geo point |
📖 Free, searchable command reference. Bookmark this page for quick access.