Skip to content

MongoDB Cheat Sheet

MongoDB is a document database and mongosh is the modern MongoDB shell used to run commands and queries. This MongoDB cheatsheet provides an advanced, categorized reference of mongosh commands, CRUD operations, query/update operators, aggregation pipeline stages, indexing, and operational helpers.

Shell startup and session control

Start mongosh

Open a connection to a MongoDB deployment and enter an interactive shell.

mongosh
mongosh "mongodb://host:27017"
mongosh "mongodb://user:pass@host:27017/db?authSource=admin"
mongosh "mongodb://localhost:27017"

Exit mongosh

Exit the interactive mongosh session.

exit
exit

Database help and collection help

Show help for database or collection methods.

db.help()
db.<collection>.help()
db.help()
db.users.help()

Database and collection navigation

Show databases

List databases visible to the current user.

show dbs
show databases
show dbs

Use a database

Switch the current database context.

use <dbName>
use appdb
db

Show collections

List collections in the current database.

show collections
use appdb
show collections

Drop the current database

Delete the currently selected database.

db.dropDatabase()
use testdb
db.dropDatabase()

Create operations

Insert one document

Insert a single document into a collection (creates collection if missing).

db.collection.insertOne(document)
db.users.insertOne({ name: "Chris", age: 24, place: "NYC" })

Insert many documents

Insert multiple documents into a collection.

db.collection.insertMany([doc1, doc2, ...])
db.users.insertMany([{ age: 24 }, { age: 38 }])

Read operations

Find documents

Return a cursor to documents matching the filter.

db.collection.find(filter, projection, options)
db.users.find({ place: "NYC" })

Find with projection include fields

Include specific fields in results by setting them to 1.

db.collection.find(filter, { field1: 1, field2: 1 })
db.users.find({ place: "NYC" }, { status: 1, item: 1 })

Find with projection exclude fields

Exclude specific fields (including _id) by setting them to 0.

db.collection.find(filter, { field1: 1, field2: 1, _id: 0 })
db.collection.find(filter, { fieldToExclude: 0 })
db.users.find({ place: "NYC" }, { status: 1, item: 1, _id: 0 })

Sort results

Order results by fields (1 ascending, -1 descending).

db.collection.find(filter).sort({ field1: 1, field2: -1 })
db.users.find({}).sort({ name: 1, age: -1 })

Limit and skip

Paginate results by limiting output and skipping an offset.

db.collection.find(filter).limit(n)
db.collection.find(filter).skip(n)
db.users.find({}).sort({ _id: 1 }).skip(20).limit(10)

Comparison query operators

Equality and inequality operators

Match values by equality and inequality.

{ field: { $eq: value } }
{ field: { $ne: value } }
db.users.find({ system: { $eq: "macOS" } })
db.users.find({ place: { $ne: "NYC" } })

Range operators

Match values by greater/less comparisons.

{ field: { $gt: value } }
{ field: { $gte: value } }
{ field: { $lt: value } }
{ field: { $lte: value } }
db.users.find({ age: { $gte: 21, $lt: 65 } })

Set membership operators

Match values in or not in an array of values.

{ field: { $in: [v1, v2] } }
{ field: { $nin: [v1, v2] } }
db.users.find({ place: { $in: ["NYC", "SF"] } })
db.users.find({ place: { $nin: ["NYC", "SF"] } })

Logical and expression filters

$and and $or

Combine multiple filter conditions.

{ $and: [ { cond1 }, { cond2 } ] }
{ $or:  [ { cond1 }, { cond2 } ] }
db.users.find({ $and: [{ age: 12 }, { name: "Kyle" }] })
db.users.find({ $or: [{ age: 12 }, { name: "Kyle" }] })

$not and $exists

Negate a condition or require a field to exist.

{ field: { $not: { $eq: value } } }
{ field: { $exists: true } }
db.users.find({ name: { $not: { $eq: "Kyle" } } })
db.users.find({ name: { $exists: true } })

$expr

Compare values between fields or compute expressions in filters.

{ $expr: { $gt: ["$fieldA", "$fieldB"] } }
db.users.find({ $expr: { $gt: ["$balance", "$debt"] } })

Update operations

Update one document

Modify the first document matching the filter.

db.collection.updateOne(filter, update, options)
db.users.updateOne({ age: 25 }, { $set: { age: 32 } })

Update many documents

Modify all documents matching the filter.

db.collection.updateMany(filter, update, options)
db.users.updateMany({ age: 27 }, { $inc: { age: 3 } })

Replace one document

Replace the first matching document with a new document.

db.collection.replaceOne(filter, replacement, options)
db.users.replaceOne({ name: "Kris" }, { name: "Chris" })

Field update operators

$set and $unset

Set field values or remove fields.

{ $set: { field: value } }
{ $unset: { field: "" } }
db.users.updateOne({ age: 12 }, { $set: { name: "Hi" } })
db.users.updateOne({ age: 12 }, { $unset: { age: "" } })

$inc, $min, $max

Increment a numeric field or conditionally set min/max values.

{ $inc: { field: number } }
{ $min: { field: value } }
{ $max: { field: value } }
db.users.updateOne({ age: 22 }, { $inc: { age: 3 } })
db.scores.updateOne({ _id: 1 }, { $min: { lowScore: 150 } })
db.scores.updateOne({ _id: 1 }, { $max: { highScore: 1000 } })

$rename

Rename a field in documents.

{ $rename: { oldField: "newField" } }
db.users.updateMany({}, { $rename: { age: "years" } })

Array update operators

$push and $pull

Append to or remove from array fields.

{ $push: { arrayField: value } }
{ $pull: { arrayField: valueOrQuery } }
db.users.updateMany({}, { $push: { friends: "John" } })
db.users.updateMany({}, { $pull: { friends: "Mike" } })

Delete operations

Delete one document

Remove the first document matching the filter.

db.collection.deleteOne(filter)
db.users.deleteOne({ age: 37 })

Delete many documents

Remove all documents matching the filter.

db.collection.deleteMany(filter)
db.users.deleteMany({ age: { $lt: 18 } })

Aggregation framework

Aggregate pipeline

Run an aggregation pipeline with stages like $match, $group, $sort.

db.collection.aggregate([
  { $match: { /* filter */ } },
  { $group: { _id: "$field", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } }
])
db.users.aggregate([
  { $match: { access: "valid" } },
  { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } }
])

$project

Reshape documents by including/excluding/computing fields.

db.collection.aggregate([
  { $project: { field1: 1, field2: 1, computed: { $add: ["$a", "$b"] } } }
])
db.orders.aggregate([
  { $project: { _id: 0, order_id: 1, total: { $add: ["$subtotal", "$tax"] } } }
])

$unwind

Deconstruct an array field and output one document per element.

db.collection.aggregate([
  { $unwind: "$arrayField" }
])
db.inventory.insertOne({ _id: 1, item: "ABC1", sizes: ["S", "M", "L"] })
db.inventory.aggregate([{ $unwind: "$sizes" }])

$lookup

Join documents from another collection into an array field.

db.collection.aggregate([
  {
    $lookup: {
      from: "otherCollection",
      localField: "localKey",
      foreignField: "foreignKey",
      as: "joined"
    }
  }
])
db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "user"
    }
  }
])

$facet

Run multiple pipelines in a single stage and return a multi-result document.

db.collection.aggregate([
  {
    $facet: {
      topTags: [{ $sortByCount: "$tag" }, { $limit: 10 }],
      totals: [{ $group: { _id: null, sum: { $sum: "$amount" } } }]
    }
  }
])
db.events.aggregate([
  {
    $facet: {
      byType: [{ $sortByCount: "$type" }],
      totals: [{ $group: { _id: null, n: { $sum: 1 } } }]
    }
  }
])

Counting and distinct

estimatedDocumentCount

Return an approximate count of all documents in a collection.

db.collection.estimatedDocumentCount(options)
db.users.estimatedDocumentCount({})

countDocuments

Return an accurate count matching a filter.

db.collection.countDocuments(filter, options)
db.users.countDocuments({ place: "NYC" })

distinct

Return distinct values for a field.

db.collection.distinct(field, filter, options)
db.users.distinct("age")

Indexing

Create an index

Create indexes to support efficient queries and sorts.

db.collection.createIndex(keys, options)
db.users.createIndex({ account_creation_date: 1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.orders.createIndex({ userId: 1, createdAt: -1 })

List indexes

Inspect indexes on a collection.

db.collection.getIndexes()
db.users.getIndexes()

Drop indexes

Drop a single index or all indexes (except _id).

db.collection.dropIndex(indexName)
db.collection.dropIndexes()
db.users.dropIndex("account_creation_date_1")
db.users.dropIndexes()

TTL index

Expire documents automatically based on a date field.

db.collection.createIndex({ dateField: 1 }, { expireAfterSeconds: seconds })
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })

Partial index

Index only documents matching a filter expression.

db.collection.createIndex(
  keys,
  { partialFilterExpression: filter }
)
db.users.createIndex(
  { email: 1 },
  { partialFilterExpression: { email: { $exists: true } } }
)

Query planning and profiling

Explain a query

Inspect query plan and execution statistics for a find operation.

db.collection.find(filter).explain()
db.collection.find(filter).explain("executionStats")
db.users.find({ email: "a@example.com" }).explain("executionStats")

Show profiling results

Display the most recent operations over the profile threshold.

show profile
show profile

Replication (replica set helpers)

rs.status

Retrieve current replica set status from the member where it runs.

rs.status()
rs.status()

rs.add

Add a member to the current replica set.

rs.add(hostOrConfig)
rs.add({ host: "mongodb3.example.net:27017", priority: 0, votes: 0 })

rs.stepDown

Step down the current primary to force an election.

rs.stepDown(seconds)
rs.stepDown(60)

rs.conf and rs.reconfig

View and update replica set configuration.

rs.conf()
rs.reconfig(cfg, options)
const cfg = rs.conf()
cfg.members[0].priority = 2
rs.reconfig(cfg)

Sharding (cluster helpers)

sh.status

Display sharded cluster status and distribution summary.

sh.status()
sh.status()

sh.enableSharding

Enable sharding for a database.

sh.enableSharding("dbName")
sh.enableSharding("records")

sh.shardCollection

Shard a collection by a shard key.

sh.shardCollection("db.collection", { shardKey: 1 })
sh.shardCollection("records.users", { zipcode: 1 })

refineCollectionShardKey

Add fields as a suffix to an existing shard key.

db.adminCommand({
  refineCollectionShardKey: "db.collection",
  key: { existingKey: 1, newKey: 1 }
})
db.getSiblingDB("test").orders.createIndex({ customer_id: 1, order_id: 1 })
db.adminCommand({
  refineCollectionShardKey: "test.orders",
  key: { customer_id: 1, order_id: 1 }
})

Database commands and admin helpers

db.runCommand

Run a database command against the current database.

db.runCommand({ commandName: 1 })
db.runCommand({ ping: 1 })

db.adminCommand

Run a command against the admin database.

db.adminCommand({ commandName: 1 })
db.adminCommand({ listDatabases: 1 })

User and role management

Create a user

Create a database user with roles.

db.createUser({
  user: "user",
  pwd: "password",
  roles: [{ role: "readWrite", db: "appdb" }]
})
use appdb
db.createUser({
  user: "appuser",
  pwd: "s3cr3t",
  roles: [{ role: "readWrite", db: "appdb" }]
})

Authenticate a user

Authenticate to the current database.

db.auth("user", "password")
db.auth("appuser", "s3cr3t")

Grant or revoke roles

Grant or revoke roles for an existing user.

db.grantRolesToUser("user", [{ role: "roleName", db: "dbName" }])
db.revokeRolesFromUser("user", [{ role: "roleName", db: "dbName" }])
db.grantRolesToUser("appuser", [{ role: "dbAdmin", db: "appdb" }])
db.revokeRolesFromUser("appuser", [{ role: "dbAdmin", db: "appdb" }])

Create a role

Create a user-defined role with privileges.

db.createRole({
  role: "roleName",
  privileges: [{ resource: { db: "appdb", collection: "" }, actions: ["find"] }],
  roles: []
})
use appdb
db.createRole({
  role: "readUsers",
  privileges: [{ resource: { db: "appdb", collection: "users" }, actions: ["find"] }],
  roles: []
})

Show users and roles

List users and roles in the current database.

show users
show roles
use appdb
show users
show roles