MongoDB Cheat Sheet

mongosh operations — documents, queries, indexes, aggregations, backup, and the ops commands for a replica set.

Databases6 sections · 39 commands
⌘K

Connecting

5
mongosh

Connect to localhost default

mongosh 'mongodb://user:pass@host:27017/db'

Connect with credentials

mongosh 'mongodb+srv://cluster.mongodb.net/db'

Atlas-style SRV connection string

show dbs

List databases

use mydb

Switch database (creates on write)

CRUD

11
db.users.insertOne({name: 'alice', role: 'admin'})

Insert one document

db.users.insertMany([{..},{..}])

Insert multiple

db.users.find({role: 'admin'})

Query with filter

db.users.find({}, {name: 1, _id: 0})

Projection (name only)

db.users.findOne({name: 'alice'})

First match only

db.users.countDocuments({role: 'admin'})

Count matches

db.users.updateOne({name:'alice'}, {$set: {age: 30}})

Update one field

db.users.updateMany({}, {$inc: {visits: 1}})

Bulk increment

db.users.deleteOne({name: 'alice'})

Delete one

db.users.deleteMany({role: 'guest'})

Delete many

db.users.find({age: {$gt: 21}})

Comparison operators

Indexes & Performance

7
db.users.createIndex({email: 1}, {unique: true})

Unique index

db.users.createIndex({location: '2dsphere'})

Geospatial index

db.users.getIndexes()

Existing indexes

db.users.explain('executionStats').find({email: 'x'})

Explain a query

db.users.dropIndex({email: 1})

Drop an index

db.currentOp()

Running operations

db.killOp(OPID)

Terminate an operation

Aggregation

5
db.orders.aggregate([{ $match: { status: 'paid' } }])

Pipeline starts with a filter

db.orders.aggregate([{ $group: { _id: '$user', total: { $sum: '$amount' } } }])

Group and sum

db.orders.aggregate([{ $sort: { created: -1 } }, { $limit: 10 }])

Sort then limit

db.orders.aggregate([{ $unwind: '$items' }])

Flatten arrays

db.orders.aggregate([{ $lookup: { from: 'users', localField: 'user', foreignField: '_id', as: 'u' } }])

Join collections

Backup & Restore

4
mongodump --db DB --out dump/

Backup a database

mongorestore --db DB dump/DB/

Restore from a dump

mongodump --gzip --archive=backup.gz

Compressed archive backup

mongorestore --gzip --archive=backup.gz

Restore from archive

Ops & Replica Set

7
db.serverStatus()

Server health counters

db.adminCommand({listDatabases: 1})

Admin command

rs.status()

Replica set health

rs.conf()

Replica set config

rs.stepDown()

Step down as primary

db.adminCommand({replSetGetStatus: 1})

Replication timestamps

mongosh --eval 'db.stats()'

One-off stats