Contents

MongoDB Cheat Sheet

This MongoDB cheat sheet covers 30 sections: mongosh commands, BSON types, schema design, find and the query operators, update operators and arrays, the aggregation pipeline, indexes and explain(), transactions, change streams, search and vector search, replica sets, sharding, mongodump and the error codes you will actually meet. Search it, filter it by your server version, copy any line with one click, and format, lint or convert a query from SQL without leaving the page.

By Bogdan SanduUpdated September 29, 2026

Checked against the MongoDB 9.0 and 8.0 documentation and release notes

Format, lint and convert queries

Ctrl+Enter formats. Lint flags updates with an empty filter, updates without an operator, _id compared as a string, unanchored or case insensitive regex, $where, operators missing their $, large skip values, $match after $group, $out or $merge that is not last and the legacy count() and insert() methods. SQL to MongoDB handles SELECT with JOIN, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT, plus INSERT, UPDATE and DELETE. Read explain() takes queryPlanner or executionStats output and suggests an index that follows the ESR rule. mongosh to PyMongo rewrites find, aggregate, update and index calls with Python types and keyword options.
Output

          
Paste a query, a pipeline, SQL, explain() output, CSV or JSON above, then pick an action.

mongodump, connection and index builders

Commands

          

Install & Connect

Install MongoDB

A throwaway server in Docker, with a root user and a volume for the data

Docker

The official image creates the root user only on the first start, when /data/db is empty. Changing the environment variables later does nothing to an existing volume, which is the usual reason a new password does not work.

docker run -d --name mongo -p 127.0.0.1:27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=root \
  -e MONGO_INITDB_ROOT_PASSWORD="$(openssl rand -base64 24)" \
  -v mongo-data:/data/db \
  mongo:8.0

docker exec -it mongo mongosh -u root -p            # prompts for the password

docker logs -f mongo

A single node replica set, so transactions and change streams work locally

Docker

docker run -d --name mongo-rs -p 127.0.0.1:27017:27017 mongo:8.0 --replSet rs0 --bind_ip_all
docker exec -it mongo-rs mongosh --eval "rs.initiate()"
mongosh "mongodb://localhost:27017/?replicaSet=rs0&directConnection=true"{ info2: 'no configuration specified. Using a default configuration for the set', me: '1a2b3c4d5e6f:27017', ok: 1 }

Ubuntu 24.04 from the official repository (the distribution package is old or missing)

Ubuntu

The mongodb-org package installs mongod, mongos, mongosh and the Database Tools. Swap 8.0 for the release you want in all three places; the repository path and the key are per major version.

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \

  sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | \
  sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo apt-get update && sudo apt-get install -y mongodb-org
sudo systemctl enable --now mongod
systemctl status mongod● mongod.service - MongoDB Database Server
     Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; preset: enabled)
     Active: active (running) since Mon 2026-09-29 09:12:40 EEST; 4s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 48213 (mongod)

Homebrew, from MongoDB's own tap

macOS

brew tap mongodb/brew
brew install mongodb-community            # or mongodb-community@8.0 to pin a version

brew services start mongodb-community
brew install mongosh mongodb-database-tools==> Successfully started `mongodb-community` (label: homebrew.mxcl.mongodb-community)

A local Atlas deployment with Search and Vector Search, or a free cloud cluster

Atlas CLIAtlas only

brew install mongodb-atlas-cli
atlas deployments setup local1 --type local      # runs in Docker or Podman, includes mongot

atlas deployments connect local1 --connectWith mongosh

atlas setup                                       # sign in and create a free M0 cluster

atlas clusters connectionStrings describe Cluster0

Connect With mongosh

Connection strings: local, replica set, Atlas

Pass -u without -p and mongosh asks for the password, so it never lands in the shell history or in ps output. mongodb+srv looks up the host list and options in DNS SRV and TXT records and turns TLS on by default.

mongosh                                                        # mongodb://127.0.0.1:27017

mongosh "mongodb://localhost:27017/shop"
mongosh "mongodb://db1:27017,db2:27017,db3:27017/shop?replicaSet=rs0&tls=true" -u app
mongosh "mongodb+srv://cluster0.example.net/shop" --username app   # prompts for the password

mongosh "$MONGODB_URI" --quiet --eval "db.runCommand({ ping: 1 })"{ ok: 1 }

Where am I

db                                  // current database

db.getMongo()                       // connection

db.version()                        // server version

db.hello()                          // role in the replica set, limits

db.runCommand({ connectionStatus: 1 }).authInfoshop
mongodb+srv://<credentials>@cluster0.example.net/shop
8.0.32

Common startup options

--apiVersion 1 with --apiStrict rejects commands outside the Stable API, which is how you check that a script will keep working after a server upgrade.

mongosh "$MONGODB_URI" --file seed.js          # run a script and exit

mongosh "$MONGODB_URI" --nodb                   # a JavaScript REPL without a connection

mongosh "$MONGODB_URI" --apiVersion 1 --apiStrict
mongosh "$MONGODB_URI" --tls --tlsCAFile ca.pem --tlsCertificateKeyFile client.pem
mongosh "$MONGODB_URI" --authenticationMechanism MONGODB-X509

mongosh Basics

Navigate

Databases and collections

use shop does not create anything. A database appears in show dbs only after its first collection gets a document or an index, which is why a freshly created database seems to vanish.

show dbs                     // databases that hold data

use shop                     // switch; created on the first write

show collections
db.getCollectionNames()
db.orders.find().limit(3)
db.getCollection('order-items').find()      // names with dashes or dotsadmin    100.00 KiB
config   240.00 KiB
local      1.02 GiB
shop      42.61 MiB

Help at every level

help
db.help()
db.orders.help()
db.orders.find().help()
db.orders.find            // print the method without calling it

Leave the shell

exit
quit()
// or Ctrl+D; Ctrl+C twice while nothing is running

Results and Cursors

Iterate a cursor

find() returns a cursor, not an array. The server sends documents in batches and the cursor fetches the next batch as you iterate; toArray() pulls every batch into memory, so keep it for small results.

db.orders.find({ status: 'paid' })   // prints the first 20 documents

it                                   // the next batch

config.set('displayBatchSize', 50)
db.orders.find().toArray()           // everything, into memory

db.orders.find().forEach(d => print(d._id))Type "it" for more

Printing and JSON

printjson(db.orders.findOne())
print(EJSON.stringify(db.orders.findOne(), null, 2))   // Extended JSON, keeps types

db.orders.findOne({}, { _id: 0, total: 1 })
JSON.stringify({ at: new Date() })                      // plain JSON loses the type{
  "_id": { "$oid": "66f9a1c2e4b0d7a1c3f2e9b4" },
  "total": { "$numberDecimal": "129.90" },
  "created_at": { "$date": "2026-09-14T08:12:44.120Z" }
}

Scripts and Configuration

Run scripts and one liners

--json=relaxed or --json=canonical prints the result of --eval as Extended JSON, which is the clean way to pipe mongosh output into jq or another program.

mongosh "$MONGODB_URI" --quiet --eval 'db.orders.countDocuments({ status: "new" })'
mongosh "$MONGODB_URI" --quiet --json=relaxed --eval 'db.orders.findOne()' > one.json
load('scripts/seed.js')              // inside mongosh42

Settings and the startup file

config                                    // every setting

config.set('editor', 'code --wait')
edit myPipeline                           // edit a variable in that editor

config.set('inspectDepth', 10)
config.set('historyLength', 5000)
// ~/.mongoshrc.js runs at every start:

prompt = () => `${db.getName()}> `

Tab completion, history, snippets

db.ord<Tab>                  // completes collection names and methods

// Ctrl+R searches the history in ~/.mongodb/mongosh/

snippet search               // community snippets package manager

snippet install analyze-schema

Connect to a second server from the same shell

const other = connect('mongodb://reports.internal:27017/archive')
other.orders.countDocuments()
const m = new Mongo('mongodb://db2.internal:27017')
m.getDB('shop').orders.findOne()
db.getSiblingDB('admin').runCommand({ listDatabases: 1, nameOnly: true })

Timing and Output

Time a query from the shell

The time includes the network round trips and building the documents in the shell, so for the server side cost read executionTimeMillis from explain('executionStats').

const t0 = Date.now()
db.orders.find({ status: 'paid' }).toArray().length
print(`${Date.now() - t0} ms`)311
42 ms

Databases & Collections

Databases

Create, inspect and drop

dataSize is the uncompressed size of the documents; storageSize is what they take on disk after WiredTiger compression, usually a third to a fifth of it. Neither shrinks after deletes until the space is reused or the collection is compacted.

use shop
db.orders.insertOne({ status: 'new' })     // the database now exists

db.stats()
db.getSiblingDB('reports').getCollectionNames()
db.dropDatabase()                          // the current database, no undo{
  db: 'shop',
  collections: 12,
  views: 1,
  objects: 1204331,
  avgObjSize: 412.8,
  dataSize: 497150226,
  storageSize: 188469248,
  indexes: 31,
  indexSize: 96710656,
  ok: 1
}

Database name rules

// max 64 bytes; no / \ . " $ * < > : | ? space or null character

// case matters but two databases cannot differ only by case (Shop vs shop)

// admin, local and config are reserved

Collections

Create explicitly with options, or implicitly on the first insert

db.createCollection('orders')
db.createCollection('events', { validator: { $jsonSchema: { required: ['type', 'at'] } } })
db.orders.renameCollection('orders_2025')
db.orders_tmp.drop()
db.getCollectionInfos({ name: 'orders' }){ ok: 1 }

Size of a collection and its indexes

The storageStats fields come from $collStats, which is also what db.collection.stats() calls behind the scenes in mongosh. The scale option turns bytes into MiB for easier reading.

db.orders.aggregate([{ $collStats: { storageStats: { scale: 1024 * 1024 } } }])
  .next().storageStats
db.orders.totalIndexSize()
db.orders.estimatedDocumentCount(){ size: 474, count: 1204331, avgObjSize: 412, storageSize: 179, totalIndexSize: 92, nindexes: 5, ... }

Modify options later with collMod

db.runCommand({ collMod: 'orders', validationLevel: 'moderate' })
db.runCommand({ collMod: 'sessions', index: { keyPattern: { last_seen: 1 }, expireAfterSeconds: 3600 } })
db.runCommand({ collMod: 'orders', changeStreamPreAndPostImages: { enabled: true } })

Views, Capped and Clustered Collections

A read only view defined by a pipeline

A standard view stores only the pipeline and runs it on every read, so it always shows current data and uses the indexes of the source collection. For precomputed results, write them with $merge into an on demand materialized view.

db.createView('paid_orders', 'orders', [
  { $match: { status: 'paid' } },
  { $project: { customer_id: 1, total: 1, created_at: 1 } }
])
db.paid_orders.find({ total: { $gt: 100 } })[
  { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), customer_id: ObjectId('66f99f10e4b0d7a1c3f2d001'), total: 129.9, created_at: ISODate('2026-09-14T08:12:44.120Z') }
]

Capped collection: fixed size, insertion order, oldest out first

Capped collections cannot shard and documents cannot grow in place. For expiring data, a TTL index on a normal collection is usually the better tool.

db.createCollection('log', { capped: true, size: 64 * 1024 * 1024, max: 100000 })
db.log.find().sort({ $natural: -1 }).limit(10)     // newest first

db.log.isCapped()[ { _id: ObjectId('66f9b0e1e4b0d7a1c3f2f001'), level: 'warn', msg: 'slow request', at: ISODate('2026-09-29T11:02:09.441Z') }, ... ]
true

Clustered collection: documents stored in _id order

With a clustered collection there is no separate _id index, so range queries on a time based _id and TTL deletes are cheaper. The key must be _id, and it is set only at creation.

db.createCollection('events', {
  clusteredIndex: { key: { _id: 1 }, unique: true },
  expireAfterSeconds: 60 * 60 * 24 * 30
})

Inspect Collections

Names and types of every collection and view

db.getCollectionInfos().map(c => ({ name: c.name, type: c.type, capped: !!c.options.capped }))[
  { name: 'orders', type: 'collection', capped: false },
  { name: 'paid_orders', type: 'view', capped: false },
  { name: 'metrics', type: 'timeseries', capped: false },
  { name: 'log', type: 'collection', capped: true }
]

BSON Types

ObjectId and Dates

ObjectId: 12 bytes, sortable by creation time

An ObjectId is a 4 byte timestamp in seconds, a 5 byte random value per process and a 3 byte counter. It is generated by the driver, not the server, so _id order is roughly insert order but not strictly across clients.

const id = ObjectId()
id.getTimestamp()
ObjectId('66f9a1c2e4b0d7a1c3f2e9b4').toHexString()
db.orders.find({ _id: { $gt: ObjectId.createFromTime(Math.floor(Date.now() / 1000) - 3600) } })   // last hourISODate('2026-09-29T18:40:34.000Z')

Dates are UTC milliseconds; Date() without new is a string

A date stored as a string still sorts, but comparisons with ISODate values never match and date operators fail on it. Store dates as BSON dates and convert to the user's time zone only when displaying or with the timezone option of the date operators.

new Date()                             // Date, stored as a BSON date

ISODate('2026-09-29T10:00:00Z')        // same type, mongosh helper

Date()                                 // a string: do not store this

db.orders.find({ created_at: { $gte: ISODate('2026-09-01'), $lt: ISODate('2026-10-01') } })ISODate('2026-09-29T19:40:34.512Z')
ISODate('2026-09-29T10:00:00.000Z')
Mon Sep 29 2026 22:40:34 GMT+0300 (Eastern European Summer Time)

Numbers

Int32, Long, Double, Decimal128

The legacy mongo shell stored every number as a double; mongosh stores whole numbers that fit in 32 bits as int32 and others as double. Queries compare numbers across types by value, so 3, Long('3') and 3.0 all match { qty: 3 }.

db.t.insertOne({
  qty: 3,                            // mongosh sends whole numbers as int32

  views: Long('9007199254740993'),   // 64 bit integer, beyond JavaScript precision

  ratio: 0.25,                       // double

  price: Decimal128('19.99')         // exact decimal for money

})
db.t.find({ qty: { $type: 'int' } })[
  {
    _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9c2'),
    qty: 3,
    views: Long('9007199254740993'),
    ratio: 0.25,
    price: Decimal128('19.99')
  }
]

Money: Decimal128, or integer cents

0.1 + 0.2                                    // 0.30000000000000004

db.products.updateOne({ sku: 'OAK-1' }, { $inc: { price: Decimal128('0.10') } })
db.products.insertOne({ sku: 'OAK-2', price_cents: 1999 })0.30000000000000004

Other Types

UUID, binary data, booleans, null and missing fields

UUID()                                         // random v4, binary subtype 4

UUID('4f6c8d0e-2b1a-4c3d-9e8f-7a6b5c4d3e2f')
BinData(0, 'aGVsbG8=')
db.users.find({ deleted_at: null })            // null or missing

db.users.find({ deleted_at: { $exists: false } })   // missing only

db.users.find({ deleted_at: { $type: 'null' } })    // explicitly null onlyUUID('3b241101-e2bb-4255-8caf-4136c566a962')
UUID('4f6c8d0e-2b1a-4c3d-9e8f-7a6b5c4d3e2f')
Binary.createFromBase64('aGVsbG8=', 0)

$type names and numbers

TypeAliasNumber
Doubledouble1
Stringstring2
Objectobject3
Arrayarray4
Binary databinData5
ObjectIdobjectId7
Booleanbool8
Datedate9
Nullnull10
Regular expressionregex11
32 bit integerint16
Timestamptimestamp17
64 bit integerlong18
Decimal128decimal19
Any numbernumbernone

Sort and comparison order across types

A field that holds numbers in some documents and strings in others sorts into two separate groups, and a range query such as $gt: 5 only matches values of the same type class. Mixed types in one field are usually a bug in the writer.

// MinKey < null < numbers < strings < objects < arrays < binData

//   < ObjectId < booleans < dates < timestamps < regex < MaxKey

db.t.find().sort({ v: 1 })      // mixed types come out in this order

Limits worth knowing

// document: 16 MiB, nesting depth: 100 levels

// field names may contain . and $ since 5.0, but most operators need $getField for them

Object.bsonsize(db.orders.findOne())       // bytes of one document1488

Fix Types in Place

Convert string prices to Decimal128 and string dates to dates

A pipeline update converts every matching document on the server in one pass. Run it with the $type filter so a second run touches nothing.

db.products.updateMany({ price: { $type: 'string' } }, [{ $set: { price: { $toDecimal: '$price' } } }])
db.orders.updateMany({ created_at: { $type: 'string' } }, [{ $set: { created_at: { $toDate: '$created_at' } } }]){ acknowledged: true, insertedId: null, matchedCount: 212, modifiedCount: 212, upsertedCount: 0 }
{ acknowledged: true, insertedId: null, matchedCount: 38, modifiedCount: 38, upsertedCount: 0 }

Schema Design

Embed or Reference

Embed what is read together and bounded in size

A document is read and written atomically, so data that is always used together belongs in one document. The limit is size and growth: embed when the child count is bounded and small.

{
  _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'),
  customer_id: ObjectId('66f99f10e4b0d7a1c3f2d001'),
  status: 'paid',
  shipping: { city: 'Cluj-Napoca', country: 'RO' },   // one to one: embed

  items: [                                              // one to few: embed

    { sku: 'OAK-1', qty: 2, price: Decimal128('19.99') }
  ],
  total: Decimal128('39.98')
}

Reference what grows without limit or is shared

// customers: { _id, name, email }

// orders:    { _id, customer_id, ... }    one to many with an unbounded many

db.orders.find({ customer_id: cid }).sort({ created_at: -1 }).limit(20)
db.orders.createIndex({ customer_id: 1, created_at: -1 })[
  { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), customer_id: ObjectId('66f99f10e4b0d7a1c3f2d001'), status: 'paid', total: 129.9, created_at: ISODate('2026-09-14T08:12:44.120Z') },
  { _id: ObjectId('66e0c4d1e4b0d7a1c3f2c812'), customer_id: ObjectId('66f99f10e4b0d7a1c3f2d001'), status: 'shipped', total: 54, created_at: ISODate('2026-08-02T15:40:11.002Z') }
]

A rule of thumb

RelationshipTypical model
One to oneembed the child document
One to few (under a few hundred)embed an array
One to many (thousands)array of ids in the parent, or parent id in the child
One to squillions (logs, events)parent id in the child, never an array in the parent
Many to manyarrays of ids on one or both sides

Design Patterns

Extended reference: copy the few fields you display

Copying the customer name into each order avoids a $lookup on every list page. The cost is updating the copies when the name changes, so copy only fields that rarely change.

{ _id: 1, customer: { _id: cid, name: 'Ana Pop', country: 'RO' }, total: 129.9 }

Subset: the latest items embedded, the rest elsewhere

{ _id: 'OAK-1', name: 'Oak table', recent_reviews: [ /* last 10 */ ], review_count: 1482 }
db.reviews.find({ product_id: 'OAK-1' }).sort({ at: -1 }).skip(10)

Computed: keep totals up to date on write

db.products.updateOne(
  { _id: 'OAK-1' },
  { $inc: { review_count: 1, rating_sum: 5 } }
){ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }

Bucket: group many small readings into one document per period

One document per reading means millions of small documents and index entries; one per sensor per period cuts both. For new time series data, a time series collection does this bucketing for you.

db.readings.updateOne(
  { sensor: 's1', day: ISODate('2026-09-29'), n: { $lt: 200 } },
  { $push: { r: { t: new Date(), v: 21.4 } }, $inc: { n: 1 } },
  { upsert: true }
){ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }

Schema versioning and polymorphic documents

{ _id: 1, schema_version: 2, name: { first: 'Ana', last: 'Pop' } }
{ _id: 2, name: 'Radu Ionescu' }                          // version 1, migrated lazily

db.people.find({ schema_version: { $ne: 2 } }).limit(1000)   // batch migration

Anti patterns

// unbounded arrays that grow forever (followers, logs)

// one collection per customer or per day: thousands of collections and indexes

// huge documents read in full to show two fields

// $lookup on every request to rebuild a relational schema

// fields that hold different types in different documents

Insert Documents

insertOne and insertMany

Insert one document; _id is added when missing

db.customers.insertOne({ name: 'Ana Pop', email: 'ana@example.com', country: 'RO', created_at: new Date() }){ acknowledged: true, insertedId: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4') }

Insert many; ordered: false keeps going after an error

With the default ordered: true, the first failing document stops the batch and the rest are not inserted. With ordered: false the server tries every document and reports all errors together, which is what you want for bulk loads with possible duplicates.

db.products.insertMany([
  { sku: 'OAK-1', name: 'Oak table', price: Decimal128('199.00'), tags: ['wood', 'table'] },
  { sku: 'ASH-2', name: 'Ash chair', price: Decimal128('79.50'), tags: ['wood', 'chair'] }
], { ordered: false }){
  acknowledged: true,
  insertedIds: { '0': ObjectId('66f9a1c2e4b0d7a1c3f2e9b5'), '1': ObjectId('66f9a1c2e4b0d7a1c3f2e9b6') }
}

Duplicate key error

Code 11000 is the one to catch in application code: it means a unique index rejected the write, so turn it into a friendly already exists message or retry as an update.

db.customers.createIndex({ email: 1 }, { unique: true })
db.customers.insertOne({ email: 'ana@example.com' })MongoServerError: E11000 duplicate key error collection: shop.customers index: email_1 dup key: { email: "ana@example.com" }

Write Concern

How many members must confirm a write

Since 5.0 the default write concern is majority for most replica sets, so an acknowledged write survives the loss of the primary. w: 1 is faster but a write acknowledged only by the primary can be rolled back after a failover.

db.orders.insertOne(doc, { writeConcern: { w: 'majority', wtimeout: 5000 } })
db.orders.insertOne(doc, { writeConcern: { w: 1 } })          // primary only

db.adminCommand({ getDefaultRWConcern: 1 })

Change the cluster default

db.adminCommand({
  setDefaultRWConcern: 1,
  defaultWriteConcern: { w: 'majority' },
  defaultReadConcern: { level: 'majority' }
})

Bulk Loading Files

mongoimport from JSON, JSON arrays and CSV

mongoimport --uri "$MONGODB_URI" --collection products --file products.json          # one document per line

mongoimport --uri "$MONGODB_URI" --collection products --jsonArray --file products.json
mongoimport --uri "$MONGODB_URI" --collection products --type csv --headerline --file products.csv
mongoimport --uri "$MONGODB_URI" --collection products --type csv --headerline \
  --mode upsert --upsertFields sku --file products.csv2026-09-29T10:14:02.118+0300	connected to: mongodb+srv://[**REDACTED**]@cluster0.example.net/shop
2026-09-29T10:14:03.402+0300	4812 document(s) imported successfully. 0 document(s) failed to import.

Typed CSV columns

Without types, CSV values that look like numbers become numbers and everything else becomes a string, so a SKU such as 00123 loses its leading zeros. The toolbox's CSV to insertMany shows how each column will be typed before you load it.

mongoimport --uri "$MONGODB_URI" -c products --type csv --file products.csv \
  --columnsHaveTypes --fields "sku.string(),price.decimal(),stock.int32(),added.date_go(2006-01-02)"

Custom Ids and Scripted Loads

Your own _id instead of an ObjectId

_id is always unique and always indexed, so a natural key there saves a second unique index. It cannot be changed later; to change it, insert a new document and delete the old one.

db.products.insertOne({ _id: 'OAK-1', name: 'Oak table' })          // natural key

db.events.insertOne({ _id: UUID(), type: 'signup', at: new Date() })
db.order_items.insertOne({ _id: { order: 9001, line: 1 }, sku: 'OAK-1', qty: 2 })   // compound key{ acknowledged: true, insertedId: 'OAK-1' }

Generate test data in batches

const batch = []
for (let i = 1; i <= 100000; i++) {
  batch.push({ n: i, status: ['new', 'paid', 'shipped'][i % 3], total: Math.round(Math.random() * 50000) / 100, created_at: new Date(Date.now() - i * 60000) })
  if (batch.length === 1000) { db.orders_test.insertMany(batch, { ordered: false }); batch.length = 0 }
}
if (batch.length) db.orders_test.insertMany(batch)
db.orders_test.countDocuments()100000

Query Operators

Filters

Equality and comparison

db.orders.find({ status: 'paid' })
db.orders.find({ total: { $gte: 100, $lt: 500 } })
db.orders.find({ status: { $in: ['paid', 'shipped'] } })
db.orders.find({ status: { $ne: 'cancelled' } })       // also matches documents without status

db.orders.findOne({ _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4') }){
  _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'),
  customer_id: ObjectId('66f99f10e4b0d7a1c3f2d001'),
  status: 'paid',
  total: 129.9,
  created_at: ISODate('2026-09-14T08:12:44.120Z')
}

AND is implicit; OR needs $or

$and is only needed when the same field or the same operator appears twice, because a JavaScript object cannot hold the same key twice: { $or: ..., $or: ... } silently keeps only the last one.

db.orders.find({ status: 'paid', country: 'RO' })
db.orders.find({ $or: [{ status: 'paid' }, { total: { $gt: 1000 } }] })
db.orders.find({ $and: [{ $or: [{ a: 1 }, { b: 1 }] }, { $or: [{ c: 1 }, { d: 1 }] }] })
db.orders.find({ total: { $not: { $gt: 100 } } })       // also matches missing total

Embedded documents: dotted path versus exact match

Matching a whole embedded document requires the exact fields in the exact order, so it breaks the moment a field is added. Use dotted paths for almost everything.

db.orders.find({ 'shipping.country': 'RO' })               // field inside

db.orders.find({ shipping: { city: 'Cluj', country: 'RO' } }) // whole document, same field order

Count and distinct

db.orders.countDocuments({ status: 'paid' })
db.orders.estimatedDocumentCount()              // metadata, fast, no filter

db.orders.distinct('status')
db.orders.distinct('shipping.country', { status: 'paid' })311
1204331
[ 'cancelled', 'new', 'paid', 'refunded', 'shipped' ]

Existence, Types and Nulls

$exists, $type and null

db.users.find({ phone: { $exists: true } })
db.users.find({ phone: { $exists: true, $ne: null } })
db.users.find({ zip: { $type: 'string' } })
db.users.find({ zip: { $type: ['int', 'long'] } })
db.users.find({ phone: null })                  // null or missing

null no longer matches undefined

MongoDB 8.0+

Old data written by very old drivers can hold the BSON undefined type. From 8.0 an equality match on null skips it, so clean such values up with { v: { $type: 'undefined' } } before upgrading.

db.t.find({ v: null })       // 8.0+: matches null and missing, not the deprecated undefined type

Dotted paths compared with null

MongoDB 9.0+

From 9.0 a dotted path that does not resolve to a non-null value evaluates as null for $eq, $ne, $in, $nin, $gte and $lte, including $lookup equality, and this changes results for arrays of scalars, nested arrays and empty arrays. Test queries that compare dotted paths with null before upgrading.

db.orders.find({ 'items.discount': null })
db.orders.find({ 'items.discount': { $in: [null, 0] } })

Regex, $expr and Other Evaluation Operators

Regular expressions

Only a case sensitive regex anchored with ^ can use an index efficiently, and then only for the prefix. A case insensitive search is better served by a collation index with strength 2 or by Atlas Search.

db.users.find({ email: /@example\.com$/ })
db.users.find({ name: /^ana/i })
db.users.find({ name: { $regex: '^ana', $options: 'i' } })
db.users.find({ sku: { $regex: '^OAK-' } })          // anchored and case sensitive: uses an index[ { _id: ObjectId('66f99f10e4b0d7a1c3f2d001'), name: 'Ana Pop', email: 'ana@example.com', country: 'RO' } ]

$expr: compare two fields of the same document

db.products.find({ $expr: { $lt: ['$stock', '$reorder_level'] } })
db.orders.find({ $expr: { $gt: [{ $size: '$items' }, 10] } })
db.orders.find({ $expr: { $eq: [{ $year: '$created_at' }, 2026] } })[ { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9d7'), sku: 'ELM-3', name: 'Elm shelf', stock: 2, reorder_level: 5 } ]

$mod, bitwise, $jsonSchema in a query

db.orders.find({ number: { $mod: [100, 0] } })
db.users.find({ flags: { $bitsAllSet: [0, 2] } })
db.users.find({ $jsonSchema: { required: ['email'], properties: { email: { bsonType: 'string' } } } })

$where: server side JavaScript

$where, $function and $accumulator were deprecated in 8.0 and re-enabled in 9.0 on a WebAssembly engine with stronger sandboxing. They still cannot use indexes and are slower than $expr, and some deployments disable JavaScript with security.javascriptEnabled: false.

db.orders.find({ $where: 'this.total > this.budget' })        // prefer $expr

Query Operator Reference

The operators by group

GroupOperators
Comparison$eq $ne $gt $gte $lt $lte $in $nin
Logical$and $or $nor $not
Element$exists $type
Evaluation$expr $regex $mod $text $jsonSchema $where
Array$all $elemMatch $size
Geospatial$geoWithin $geoIntersects $near $nearSphere
Bitwise$bitsAllSet $bitsAnySet $bitsAllClear $bitsAnyClear

Projection, Sort, Paging

Projection

Include or exclude fields

A projection cannot mix 1 and 0 except for _id. Projecting only the fields you show cuts network time, and if every field is in the index the query can be covered and never read the documents.

db.customers.find({}, { name: 1, email: 1 })             // plus _id

db.customers.find({}, { name: 1, email: 1, _id: 0 })
db.customers.find({}, { password_hash: 0, tokens: 0 })   // everything else

db.orders.find({}, { 'shipping.city': 1 })[ { name: 'Ana Pop', email: 'ana@example.com' }, { name: 'Radu Ionescu', email: 'radu@example.com' } ]

Arrays and computed fields in a projection

db.posts.find({}, { title: 1, comments: { $slice: -3 } })                 // last 3

db.orders.find({ 'items.sku': 'OAK-1' }, { 'items.$': 1 })                // first matching element

db.orders.find({}, { items: { $elemMatch: { qty: { $gte: 5 } } } })
db.orders.find({}, { total: 1, year: { $year: '$created_at' } })          // aggregation expressions[
  { _id: 1, title: 'Indexes in practice', comments: [ { by: 'radu', text: 'Thanks' }, { by: 'ioana', text: 'What about TTL?' }, { by: 'ana', text: 'Next post' } ] }
]

Sort, Limit, Skip

Chain them in any order; the server applies sort, then skip, then limit

Add a unique field such as _id as the last sort key. Without it, documents with equal sort values can come back in a different order on each page, so pages repeat or skip documents.

db.orders.find({ status: 'paid' }).sort({ created_at: -1 }).limit(20)
db.orders.find().sort({ total: -1, _id: 1 }).skip(40).limit(20)
db.orders.find().sort({ $natural: -1 }).limit(5)       // storage order, no index[
  { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), status: 'paid', total: 129.9, created_at: ISODate('2026-09-29T08:12:44.120Z') },
  { _id: ObjectId('66f99e02e4b0d7a1c3f2e8a1'), status: 'paid', total: 64.5, created_at: ISODate('2026-09-29T07:58:02.311Z') },
  ...
]

Keyset pagination instead of large skip values

skip(n) still walks through the n skipped index entries or documents, so page 5000 is slow. Continuing from the last seen key uses the index directly and costs the same on every page.

const page = db.orders.find({ status: 'paid' }).sort({ created_at: -1, _id: -1 }).limit(20).toArray()
const last = page[page.length - 1]
db.orders.find({
  status: 'paid',
  $or: [
    { created_at: { $lt: last.created_at } },
    { created_at: last.created_at, _id: { $lt: last._id } }
  ]
}).sort({ created_at: -1, _id: -1 }).limit(20)

Collation, Hints and Limits

Case insensitive sorting and matching with a collation

strength 1 ignores case and accents, strength 2 ignores case only, 3 is the default and compares both. An index is used only when the query has the same collation as the index.

db.users.createIndex({ name: 1 }, { collation: { locale: 'en', strength: 2 } })
db.users.find({ name: 'ana pop' }).collation({ locale: 'en', strength: 2 })
db.users.find().sort({ name: 1 }).collation({ locale: 'ro' })              // ă, â, î, ș, ț in Romanian order

db.items.find().sort({ code: 1 }).collation({ locale: 'en', numericOrdering: true })   // 2 before 10[ { _id: ObjectId('66f99f10e4b0d7a1c3f2d001'), name: 'Ana Pop', email: 'ana@example.com' } ]

Time limits, hints, comments

A comment shows up in the profiler, currentOp and the logs, which makes it easy to trace a slow query back to the code that sent it.

db.orders.find({ status: 'new' }).maxTimeMS(2000)
db.orders.find({ status: 'new' }).hint({ status: 1, created_at: -1 })
db.orders.find({ status: 'new' }).comment('dashboard: new orders')
db.orders.find().sort({ note: 1 }).allowDiskUse()

A default time limit for every query

MongoDB 8.0+

db.adminCommand({ setClusterParameter: { defaultMaxTimeMS: { readOperations: 30000 } } })

Read preference and read concern per query

db.orders.find({ status: 'paid' }).readPref('secondaryPreferred')
db.orders.find({ status: 'paid' }).readConcern('majority')

Distinct Pages and Totals

One page of results and the total count in a single aggregation

The total still counts every matching document on each request. For large results, show the count once, cache it, or show an estimate.

db.orders.aggregate([
  { $match: { status: 'paid' } },
  { $sort: { created_at: -1, _id: -1 } },
  { $facet: { page: [{ $skip: 0 }, { $limit: 20 }], total: [{ $count: 'n' }] } }
])[ { page: [ { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), status: 'paid', total: 129.9 }, ... ], total: [ { n: 311 } ] } ]

Update Operators

Update Documents

updateOne and updateMany

matchedCount counts documents the filter found; modifiedCount counts those that actually changed. Setting a field to the value it already has matches without modifying, which is a quick way to spot no-op updates.

db.customers.updateOne({ email: 'ana@example.com' }, { $set: { country: 'DE', updated_at: new Date() } })
db.orders.updateMany({ status: 'new', created_at: { $lt: ISODate('2026-09-01') } }, { $set: { status: 'expired' } }){
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

The update needs operators, or it is a replacement

db.customers.updateOne({ _id: id }, { $set: { name: 'Ana' } })      // changes one field

db.customers.replaceOne({ _id: id }, { name: 'Ana' })               // the document is now only { _id, name }

db.customers.updateOne({ _id: id }, { name: 'Ana' })                // error: needs atomic operatorsMongoInvalidArgumentError: Update document requires atomic operators

Field Update Operators

Set, remove, increment, rename

db.products.updateOne({ sku: 'OAK-1' }, {
  $set: { 'dims.width': 120, active: true },
  $unset: { legacy_code: '' },
  $inc: { stock: -1, sold: 1 },
  $mul: { price: Decimal128('1.10') },
  $rename: { desc: 'description' },
  $currentDate: { updated_at: true }
}){ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }

Keep the lowest or highest value

db.stats.updateOne({ _id: 'day-2026-09-29' }, { $min: { low: 12.4 }, $max: { high: 31.2 } }, { upsert: true }){ acknowledged: true, insertedId: 'day-2026-09-29', matchedCount: 0, modifiedCount: 0, upsertedCount: 1 }

Update operator reference

OperatorDoes
$setset a field, creating it and any missing parent documents
$unsetremove a field
$inc / $muladd to or multiply a number
$renamerename a field
$min / $maxupdate only when the new value is lower or higher
$currentDateset to the current date or timestamp
$setOnInsertset only when an upsert inserts

Upserts and findOneAndUpdate

Insert when nothing matches

Equality fields in the filter become fields of the new document. Two clients that upsert the same key at the same moment can both insert unless a unique index covers the filter fields; with the index, one of them gets E11000 and the server retries it as an update.

db.daily_visits.updateOne(
  { page: '/pricing', day: '2026-09-29' },
  { $inc: { count: 1 }, $setOnInsert: { first_seen: new Date() } },
  { upsert: true }
){ acknowledged: true, insertedId: ObjectId('66f9a1c2e4b0d7a1c3f2e9c0'), matchedCount: 0, modifiedCount: 0, upsertedCount: 1 }

Read and modify in one atomic step

db.counters.findOneAndUpdate(
  { _id: 'invoice' },
  { $inc: { seq: 1 } },
  { upsert: true, returnDocument: 'after' }
){ _id: 'invoice', seq: 1043 }

Update the first document in a given order

MongoDB 8.0+

Before 8.0, updateOne picked whichever matching document came first, so a job queue needed findOneAndUpdate to choose the right one. The sort option works on updateOne and replaceOne.

db.jobs.updateOne(
  { state: 'queued' },
  { $set: { state: 'running', worker: 'w1', started_at: new Date() } },
  { sort: { priority: -1, created_at: 1 } }
){ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }

Update With an Aggregation Pipeline

Use other fields of the document in the update

The array form of an update runs $set, $unset, $addFields, $project, $replaceWith and a few other stages, so the new value can be computed from existing fields, which classic operators cannot do.

db.orders.updateMany({}, [
  { $set: { total: { $sum: { $map: { input: '$items', in: { $multiply: ['$$this.qty', '$$this.price'] } } } } } },
  { $set: { tier: { $switch: { branches: [{ case: { $gte: ['$total', 1000] }, then: 'gold' }], default: 'standard' } } } },
  { $unset: 'tmp' }
]){ acknowledged: true, insertedId: null, matchedCount: 1204331, modifiedCount: 1204331, upsertedCount: 0 }

Move fields into a sub document

db.users.updateMany({ street: { $exists: true } }, [
  { $set: { address: { street: '$street', city: '$city' } } },
  { $unset: ['street', 'city'] }
])

Arrays

Query Arrays

A value inside an array

db.products.find({ tags: 'wood' })                    // any element equals

db.products.find({ tags: { $all: ['wood', 'table'] } })
db.products.find({ tags: ['wood', 'table'] })         // exactly this array, this order

db.products.find({ tags: { $size: 2 } })
db.products.find({ 'tags.0': 'wood' })                // by position[ { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b5'), sku: 'OAK-1', name: 'Oak table', tags: [ 'wood', 'table' ] } ]

$elemMatch: all conditions on the same element

Conditions on dotted array paths are checked independently, so the first query matches an order with OAK-1 once and any other item with qty 5. $elemMatch forces every condition onto one element.

db.orders.find({ 'items.sku': 'OAK-1', 'items.qty': { $gte: 5 } })            // may match two different items

db.orders.find({ items: { $elemMatch: { sku: 'OAK-1', qty: { $gte: 5 } } } }) // the same item

Add and Remove Elements

$push, $addToSet, $pull, $pop

db.posts.updateOne({ _id: 1 }, { $push: { tags: 'mongodb' } })
db.posts.updateOne({ _id: 1 }, { $addToSet: { tags: { $each: ['nosql', 'db'] } } })   // no duplicates

db.posts.updateOne({ _id: 1 }, { $pull: { tags: 'db' } })
db.posts.updateOne({ _id: 1 }, { $pull: { comments: { spam: true } } })               // by condition

db.posts.updateOne({ _id: 1 }, { $pop: { tags: 1 } })                                 // last; -1 first

Keep only the latest N elements, sorted

$each with $sort and $slice caps the array in the same update, which is the usual guard against arrays that grow without limit.

db.users.updateOne({ _id: uid }, {
  $push: { recent: { $each: [{ at: new Date(), page: '/pricing' }], $sort: { at: -1 }, $slice: 10 } }
}){ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }

Insert at a position

db.lists.updateOne({ _id: 1 }, { $push: { items: { $each: ['first'], $position: 0 } } })

Update Elements in Place

Positional operators

$ updates only the first element matched by the filter. $[] updates all elements, and $[name] with arrayFilters updates every element that matches its own condition, including elements of nested arrays.

db.orders.updateOne({ _id: oid, 'items.sku': 'OAK-1' }, { $inc: { 'items.$.qty': 1 } })     // first match

db.orders.updateOne({ _id: oid }, { $set: { 'items.$[].shipped': true } })                  // every element

db.orders.updateMany(
  {},
  { $set: { 'items.$[it].price': Decimal128('17.99') } },
  { arrayFilters: [{ 'it.sku': 'OAK-1', 'it.price': { $gt: Decimal128('17.99') } }] }
){ acknowledged: true, insertedId: null, matchedCount: 1204331, modifiedCount: 48, upsertedCount: 0 }

Nested arrays

db.courses.updateOne(
  { _id: 1 },
  { $set: { 'modules.$[m].lessons.$[l].done': true } },
  { arrayFilters: [{ 'm.code': 'M2' }, { 'l.id': 7 }] }
)

Index Arrays of Documents

A compound multikey index for $elemMatch queries

db.orders.createIndex({ 'items.sku': 1, 'items.qty': 1 })
db.orders.find({ items: { $elemMatch: { sku: 'OAK-1', qty: { $gte: 5 } } } }).explain('executionStats').executionStats.totalKeysExamineditems.sku_1_items.qty_1
37

Delete & Bulk Writes

Delete

Delete one or many

db.sessions.deleteOne({ _id: sid })
db.sessions.deleteMany({ expires_at: { $lt: new Date() } })
db.jobs.findOneAndDelete({ state: 'done' }, { sort: { finished_at: 1 } }){ acknowledged: true, deletedCount: 1843 }

Empty a collection

Dropping and recreating is much faster than deleteMany({}) on millions of documents, but it also removes the indexes and validation rules, so recreate them in the same script.

db.logs.deleteMany({})     // deletes one by one, keeps indexes, slow on big collections

db.logs.drop()             // instant, drops the indexes too{ acknowledged: true, deletedCount: 4812203 }
true

Delete in batches on a busy server

One huge deleteMany generates a burst of oplog entries and replication lag. Small batches with a pause keep secondaries caught up; a TTL index does the same thing continuously.

let n
do {
  const ids = db.events.find({ at: { $lt: ISODate('2025-01-01') } }, { _id: 1 }).limit(5000).toArray().map(d => d._id)
  n = ids.length ? db.events.deleteMany({ _id: { $in: ids } }).deletedCount : 0
  sleep(200)
} while (n > 0)

Bulk Writes

Mixed writes to one collection in one round trip

db.products.bulkWrite([
  { insertOne: { document: { sku: 'ELM-3', stock: 5 } } },
  { updateOne: { filter: { sku: 'OAK-1' }, update: { $inc: { stock: -1 } } } },
  { updateMany: { filter: { stock: 0 }, update: { $set: { active: false } } } },
  { replaceOne: { filter: { sku: 'ASH-2' }, replacement: { sku: 'ASH-2', stock: 3 }, upsert: true } },
  { deleteOne: { filter: { sku: 'OLD-9' } } }
], { ordered: false }){
  acknowledged: true,
  insertedCount: 1,
  insertedIds: { '0': ObjectId('66f9a1c2e4b0d7a1c3f2e9c1') },
  matchedCount: 3,
  modifiedCount: 3,
  deletedCount: 1,
  upsertedCount: 0,
  upsertedIds: {}
}

One bulk write across several collections

MongoDB 8.0+

The bulkWrite database command added in 8.0 sends writes for several collections in one request. It is not a transaction: each write is atomic on its own, so wrap it in a transaction when all of them must succeed together.

db.getMongo().bulkWrite([
  { insertOne: { namespace: 'shop.orders', document: { _id: 9001, total: 40 } } },
  { updateOne: { namespace: 'shop.products', filter: { sku: 'OAK-1' }, update: { $inc: { stock: -1 } } } }
])

Cleanup Patterns

Remove duplicates, keeping the newest document per key

A unique index cannot be built while duplicates exist. Remove them first, then create the index straight away so new duplicates cannot appear in between.

const dupes = db.customers.aggregate([
  { $sort: { email: 1, created_at: -1 } },
  { $group: { _id: '$email', keep: { $first: '$_id' }, all: { $push: '$_id' }, n: { $sum: 1 } } },
  { $match: { n: { $gt: 1 } } }
], { allowDiskUse: true }).toArray()
const extra = dupes.flatMap(d => d.all.filter(id => !id.equals(d.keep)))
db.customers.deleteMany({ _id: { $in: extra } })
db.customers.createIndex({ email: 1 }, { unique: true }){ acknowledged: true, deletedCount: 57 }
email_1

Soft delete with a partial index

db.posts.updateOne({ _id: pid }, { $set: { deleted_at: new Date() } })
db.posts.createIndex({ author_id: 1, created_at: -1 }, { partialFilterExpression: { deleted_at: null } })
db.posts.find({ author_id: aid, deleted_at: null }).sort({ created_at: -1 })

Copy then delete: archive old documents

db.orders.aggregate([
  { $match: { created_at: { $lt: ISODate('2025-01-01') } } },
  { $merge: { into: 'orders_archive', on: '_id', whenMatched: 'keepExisting', whenNotMatched: 'insert' } }
])
db.orders.deleteMany({ created_at: { $lt: ISODate('2025-01-01') } }){ acknowledged: true, deletedCount: 402118 }

Aggregation Basics

The Pipeline

Filter, group, sort

Each stage takes the documents from the previous stage and passes its output on. Put $match and $sort first so they can use indexes; after $group or $project the documents are new and no index applies.

db.orders.aggregate([
  { $match: { status: 'paid', created_at: { $gte: ISODate('2026-01-01') } } },
  { $group: { _id: '$country', orders: { $sum: 1 }, revenue: { $sum: '$total' }, avg: { $avg: '$total' } } },
  { $sort: { revenue: -1 } },
  { $limit: 5 }
])[
  { _id: 'RO', orders: 4120, revenue: 311842.5, avg: 75.69 },
  { _id: 'DE', orders: 2987, revenue: 268120, avg: 89.76 },
  { _id: 'FR', orders: 1402, revenue: 118933.4, avg: 84.83 },
  { _id: 'IT', orders: 1215, revenue: 93004.1, avg: 76.55 },
  { _id: 'PL', orders: 998, revenue: 61277.9, avg: 61.4 }
]

SQL to aggregation

SQLAggregation
WHERE$match
GROUP BY$group
HAVING$match after $group
SELECT columns$project, $set
ORDER BY$sort
LIMIT / OFFSET$limit / $skip
JOIN$lookup
UNION ALL$unionWith
COUNT(*)$count or $group with $sum: 1
INSERT INTO ... SELECT$merge or $out

Group by several fields, then HAVING

db.orders.aggregate([
  { $group: { _id: { country: '$country', status: '$status' }, n: { $sum: 1 } } },
  { $match: { n: { $gt: 100 } } },
  { $project: { _id: 0, country: '$_id.country', status: '$_id.status', n: 1 } }
])[
  { country: 'RO', status: 'paid', n: 4120 },
  { country: 'DE', status: 'paid', n: 2987 },
  { country: 'RO', status: 'shipped', n: 1840 }
]

Count, and group everything

db.orders.aggregate([{ $match: { status: 'paid' } }, { $count: 'paid' }])
db.orders.aggregate([{ $group: { _id: null, total: { $sum: '$total' }, max: { $max: '$total' } } }])[ { paid: 311 } ]
[ { _id: null, total: 1204711.2, max: 9120 } ]

Accumulators

The $group accumulators

$first and $last depend on the order of the input documents, so sort before $group or use $top, $bottom, $topN and $bottomN, which carry their own sortBy.

db.orders.aggregate([{ $group: {
  _id: '$customer_id',
  n: { $sum: 1 },
  spent: { $sum: '$total' },
  first_order: { $min: '$created_at' },
  last_order: { $max: '$created_at' },
  statuses: { $addToSet: '$status' },
  latest3: { $topN: { n: 3, sortBy: { created_at: -1 }, output: '$_id' } },
  p90: { $percentile: { input: '$total', p: [0.9], method: 'approximate' } }
} }])[
  {
    _id: ObjectId('66f99f10e4b0d7a1c3f2d001'),
    n: 14,
    spent: 1822.4,
    first_order: ISODate('2025-03-02T10:14:00.000Z'),
    last_order: ISODate('2026-09-14T08:12:44.120Z'),
    statuses: [ 'paid', 'shipped', 'refunded' ],
    latest3: [ ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), ObjectId('66e0c4d1e4b0d7a1c3f2c812'), ObjectId('66d1a0b2e4b0d7a1c3f2b377') ],
    p90: [ 311.2 ]
  }
]

Memory limits and spilling to disk

MongoDB 9.0+

A blocking stage such as $group or $sort may use 100 MB before it spills to disk. From 9.0 there is also a limit per operation, by default the larger of 1 GB and 20% of the server memory; past it the query fails with ExceededMemoryLimit instead of pushing the server into swap.

db.orders.aggregate(pipeline, { allowDiskUse: true })       // the default since 6.0

db.orders.aggregate(pipeline, { maxTimeMS: 60000, comment: 'nightly report' })

Explain a pipeline

db.orders.explain('executionStats').aggregate(pipeline)
db.orders.aggregate(pipeline, { explain: true })

Group by Time

Revenue per month, in the business time zone

The month starts at midnight in Bucharest, which is 21:00 UTC the day before, and that is what the stored instant shows. Format it with $dateToString and the same timezone for display.

db.orders.aggregate([
  { $match: { status: 'paid' } },
  { $group: {
      _id: { $dateTrunc: { date: '$created_at', unit: 'month', timezone: 'Europe/Bucharest' } },
      revenue: { $sum: '$total' },
      orders: { $sum: 1 }
  } },
  { $sort: { _id: 1 } }
])[
  { _id: ISODate('2026-07-31T21:00:00.000Z'), revenue: 101244.8, orders: 1322 },
  { _id: ISODate('2026-08-31T21:00:00.000Z'), revenue: 96120.3, orders: 1270 }
]

Pipeline Stages

Joins and Arrays

$lookup: a left outer join

$lookup runs one query against the other collection per input document, so foreignField needs an index. _id always has one; any other field you join on needs createIndex, or the join scans the whole collection for every order.

db.orders.aggregate([
  { $match: { status: 'paid' } },
  { $lookup: { from: 'customers', localField: 'customer_id', foreignField: '_id', as: 'customer' } },
  { $unwind: '$customer' },
  { $project: { total: 1, 'customer.name': 1, 'customer.email': 1 } }
])[ { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), total: 129.9, customer: { name: 'Ana Pop', email: 'ana@example.com' } } ]

$lookup with conditions and a sub pipeline

db.customers.aggregate([
  { $lookup: {
      from: 'orders',
      localField: '_id',
      foreignField: 'customer_id',
      pipeline: [{ $match: { status: 'paid' } }, { $sort: { created_at: -1 } }, { $limit: 3 }],
      as: 'recent_paid'
  } }
])[
  {
    _id: ObjectId('66f99f10e4b0d7a1c3f2d001'),
    name: 'Ana Pop',
    recent_paid: [
      { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), status: 'paid', total: 129.9 },
      { _id: ObjectId('66d1a0b2e4b0d7a1c3f2b377'), status: 'paid', total: 212 }
    ]
  }
]

$unwind: one document per array element

db.orders.aggregate([
  { $unwind: { path: '$items', preserveNullAndEmptyArrays: true, includeArrayIndex: 'pos' } },
  { $group: { _id: '$items.sku', sold: { $sum: '$items.qty' } } },
  { $sort: { sold: -1 } }
])[
  { _id: 'OAK-1', sold: 2841 },
  { _id: 'ASH-2', sold: 1904 },
  { _id: 'ELM-3', sold: 822 }
]

$graphLookup: follow references recursively

db.employees.aggregate([
  { $match: { name: 'Ana' } },
  { $graphLookup: { from: 'employees', startWith: '$manager_id', connectFromField: 'manager_id', connectToField: '_id', as: 'chain', depthField: 'level' } }
])[
  {
    _id: 7, name: 'Ana', manager_id: 4,
    chain: [ { _id: 4, name: 'Radu', manager_id: 1, level: Long('0') }, { _id: 1, name: 'Ioana', manager_id: null, level: Long('1') } ]
  }
]

Reshaping

$set, $project, $replaceWith, $unset

db.orders.aggregate([
  { $set: { item_count: { $size: '$items' } } },
  { $unset: ['internal_notes', 'items'] },
  { $replaceWith: { $mergeObjects: ['$shipping', { order_id: '$_id', total: '$total' }] } }
])[ { city: 'Cluj-Napoca', country: 'RO', order_id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), total: 129.9 } ]

$facet: several aggregations over the same input

db.products.aggregate([
  { $match: { active: true } },
  { $facet: {
      by_category: [{ $sortByCount: '$category' }],
      price_bands: [{ $bucket: { groupBy: '$price', boundaries: [0, 50, 200, 1000], default: '1000+' } }],
      total: [{ $count: 'n' }]
  } }
])[
  {
    by_category: [ { _id: 'tables', count: 48 }, { _id: 'chairs', count: 31 } ],
    price_bands: [ { _id: 0, count: 22 }, { _id: 50, count: 40 }, { _id: 200, count: 17 } ],
    total: [ { n: 79 } ]
  }
]

$unionWith, $sample, $documents

db.orders_2025.aggregate([{ $unionWith: 'orders_2026' }, { $count: 'all' }])
db.users.aggregate([{ $sample: { size: 5 } }])
db.aggregate([{ $documents: [{ x: 1 }, { x: 2 }] }, { $set: { y: { $multiply: ['$x', 10] } } }])

Window Functions

Running totals, moving averages and ranks with $setWindowFields

db.sales.aggregate([
  { $setWindowFields: {
      partitionBy: '$store',
      sortBy: { day: 1 },
      output: {
        running: { $sum: '$amount', window: { documents: ['unbounded', 'current'] } },
        avg7: { $avg: '$amount', window: { range: [-6, 0], unit: 'day' } },
        rank: { $denseRank: {} }
      }
  } }
])[
  { store: 'cluj', day: ISODate('2026-09-27T00:00:00.000Z'), amount: 1200, running: 1200, avg7: 1200, rank: 2 },
  { store: 'cluj', day: ISODate('2026-09-28T00:00:00.000Z'), amount: 1450, running: 2650, avg7: 1325, rank: 3 },
  { store: 'cluj', day: ISODate('2026-09-29T00:00:00.000Z'), amount: 980, running: 3630, avg7: 1210, rank: 1 }
]

Fill gaps in a time series

db.sales.aggregate([
  { $densify: { field: 'day', partitionByFields: ['store'], range: { step: 1, unit: 'day', bounds: 'partition' } } },
  { $fill: { partitionBy: '$store', sortBy: { day: 1 }, output: { amount: { value: 0 } } } }
])[
  { store: 'cluj', day: ISODate('2026-09-27T00:00:00.000Z'), amount: 1200 },
  { store: 'cluj', day: ISODate('2026-09-28T00:00:00.000Z'), amount: 0 },
  { store: 'cluj', day: ISODate('2026-09-29T00:00:00.000Z'), amount: 980 }
]

Writing Results

$merge into a collection, $out to replace one

$out replaces the whole target collection atomically at the end; $merge upserts into an existing collection, which is how on demand materialized views are refreshed incrementally. Both must be the last stage.

db.orders.aggregate([
  { $match: { created_at: { $gte: ISODate('2026-09-01') } } },
  { $group: { _id: { $dateTrunc: { date: '$created_at', unit: 'day' } }, revenue: { $sum: '$total' } } },
  { $merge: { into: 'daily_revenue', on: '_id', whenMatched: 'replace', whenNotMatched: 'insert' } }
])
db.orders.aggregate([{ $match: { status: 'paid' } }, { $out: 'paid_snapshot' }])

Stage reference

StageUse it to
$matchfilter; first, to use indexes
$project, $set, $unsetchoose, add or remove fields
$group, $bucket, $sortByCountgroup and summarise
$sort, $limit, $skiporder and page
$lookup, $graphLookup, $unionWithcombine collections
$unwindone document per array element
$facetseveral pipelines on the same input
$setWindowFields, $densify, $fillwindow functions and gap filling
$replaceWithpromote a sub document to the top
$merge, $outwrite the result to a collection
$search, $vectorSearchfull text and vector search

Expressions

Conditions and Arithmetic

$cond, $ifNull, $switch

db.orders.aggregate([{ $project: {
  total: 1,
  size: { $cond: [{ $gte: ['$total', 500] }, 'large', 'small'] },
  coupon: { $ifNull: ['$coupon', 'none'] },
  band: { $switch: {
    branches: [
      { case: { $lt: ['$total', 50] }, then: 'low' },
      { case: { $lt: ['$total', 200] }, then: 'mid' }
    ],
    default: 'high'
  } }
} }])[
  { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), total: 129.9, size: 'small', coupon: 'none', band: 'mid' },
  { _id: ObjectId('66f99e02e4b0d7a1c3f2e8a1'), total: 640, size: 'large', coupon: 'AUTUMN10', band: 'high' }
]

Arithmetic

{ $add: ['$price', '$shipping'] }
{ $subtract: ['$total', '$discount'] }
{ $multiply: ['$qty', '$price'] }
{ $divide: ['$total', '$qty'] }
{ $round: [{ $multiply: ['$total', 1.19] }, 2] }
{ $mod: ['$number', 2] }
{ $abs: '$delta' }

Strings and Dates

String operators

Use the CP variants ($substrCP, $strLenCP, $indexOfCP) for text: they count Unicode code points, while $substrBytes and $strLenBytes count UTF-8 bytes and can cut a character such as ș in half.

{ $concat: ['$first', ' ', '$last'] }
{ $toLower: '$email' }
{ $trim: { input: '$name' } }
{ $split: ['$path', '/'] }
{ $substrCP: ['$name', 0, 3] }
{ $strLenCP: '$name' }
{ $regexMatch: { input: '$email', regex: /@example\.com$/ } }
{ $replaceAll: { input: '$phone', find: ' ', replacement: '' } }

Date operators with a time zone

Dates are stored in UTC. Grouping by day without a timezone puts an order placed at 01:30 in Bucharest into the previous day.

db.orders.aggregate([{ $group: {
  _id: { $dateToString: { format: '%Y-%m-%d', date: '$created_at', timezone: 'Europe/Bucharest' } },
  n: { $sum: 1 }
} }])
{ $dateTrunc: { date: '$created_at', unit: 'week', startOfWeek: 'monday' } }
{ $dateAdd: { startDate: '$created_at', unit: 'day', amount: 30 } }
{ $dateDiff: { startDate: '$created_at', endDate: '$$NOW', unit: 'day' } }
{ $dateFromString: { dateString: '$date_text', format: '%d.%m.%Y' } }
{ $year: { date: '$created_at', timezone: '+03:00' } }[ { _id: '2026-09-28', n: 412 }, { _id: '2026-09-29', n: 388 } ]

Arrays in Expressions

$map, $filter, $reduce

{ $map: { input: '$items', as: 'i', in: { $multiply: ['$$i.qty', '$$i.price'] } } }
{ $filter: { input: '$items', as: 'i', cond: { $gte: ['$$i.qty', 5] }, limit: 3 } }
{ $reduce: { input: '$items', initialValue: 0, in: { $add: ['$$value', '$$this.qty'] } } }
{ $sum: '$items.qty' }                          // simpler when you only need the sum

The position of each element

MongoDB 8.3+

{ $map: { input: '$steps', arrayIndexAs: 'i', in: { n: { $add: ['$$IDX', 1] }, step: '$$this' } } }

Other array expressions

{ $size: '$items' }
{ $arrayElemAt: ['$items', -1] }            // last

{ $in: ['vip', '$tags'] }
{ $slice: ['$items', 3] }
{ $concatArrays: ['$a', '$b'] }
{ $setUnion: ['$a', '$b'] }
{ $sortArray: { input: '$items', sortBy: { price: -1 } } }
{ $firstN: { input: '$scores', n: 3 } }

Conversion and Variables

Type conversion

MongoDB 8.0+

$toInt and the other shorthand converters throw on bad input and stop the whole pipeline. $convert with onError and onNull lets a report survive a few malformed documents.

{ $toString: '$_id' }
{ $toObjectId: '$customer_ref' }
{ $toDate: '$ts_millis' }
{ $toDecimal: '$price_text' }
{ $convert: { input: '$qty', to: 'int', onError: 0, onNull: 0 } }
{ $toUUID: '$uuid_text' }

Newer conversion helpers

MongoDB 8.3+

{ $convert: { input: 'ff', to: 'int', base: 16 } }
{ $toArray: '$tags_json' }
{ $hexHash: { input: '$email', algorithm: 'sha256' } }
{ $createObjectId: {} }

System variables and $let

'$$ROOT'           // the whole input document

'$$CURRENT'
'$$NOW'            // same value for the whole operation

'$$REMOVE'         // leave the field out

{ $let: { vars: { net: { $subtract: ['$total', '$tax'] } }, in: { $multiply: ['$$net', 0.1] } } }
{ $project: { email: { $cond: ['$public', '$email', '$$REMOVE'] } } }

Fields with dots or dollar signs in the name

{ $getField: { field: 'price.usd', input: '$$ROOT' } }
{ $setField: { field: '$unit', input: '$$ROOT', value: 'kg' } }

Indexes

Create and Manage

Create, list, drop

db.orders.createIndex({ customer_id: 1, created_at: -1 })
db.orders.createIndex({ email: 1 }, { unique: true, name: 'email_unique' })
db.orders.getIndexes()
db.orders.dropIndex('email_unique')[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { customer_id: 1, created_at: -1 }, name: 'customer_id_1_created_at_-1' },
  { v: 2, key: { email: 1 }, name: 'email_unique', unique: true }
]

Compound indexes follow the ESR rule

Equality fields narrow the scan to one contiguous range of the index, the sort fields then come out already in order so there is no in-memory sort, and range fields at the end filter within that range. Put the range field before the sort field and MongoDB must sort in memory.

// query: status = 'paid', sorted by created_at, total > 100

db.orders.createIndex({ status: 1, created_at: -1, total: 1 })
// Equality fields first, then Sort fields, then Range fields

Prefixes: one compound index serves several queries

db.orders.createIndex({ customer_id: 1, status: 1, created_at: -1 })
// used by: { customer_id }, { customer_id, status }, { customer_id, status, created_at }

// not by:  { status } alone, { created_at } alone

Build indexes on a live replica set

Since 4.2 an index build takes an exclusive lock only briefly at the start and the end, and the members of a replica set build together. It still costs CPU and IO, so build large indexes outside peak hours.

db.orders.createIndex({ sku: 1 })                 // does not block reads and writes for its duration

db.currentOp({ 'command.createIndexes': { $exists: true } })
db.orders.createIndexes([{ a: 1 }, { b: 1, c: -1 }])

Special Index Types

TTL: delete documents after a time

A background task removes expired documents about once a minute, so documents can live a little past their expiry. The field must hold a date or an array of dates; documents with a missing or non-date value never expire.

db.sessions.createIndex({ last_seen: 1 }, { expireAfterSeconds: 3600 })
db.events.createIndex({ expire_at: 1 }, { expireAfterSeconds: 0 })     // at the date in the fieldlast_seen_1
expire_at_1

Partial and unique

A partial index covers only the documents that match its filter, so it is smaller and cheaper to maintain. The planner uses it only when the query filter implies the partial filter, for example status: 'new'.

db.users.createIndex({ email: 1 }, { unique: true, partialFilterExpression: { email: { $type: 'string' } } })
db.orders.createIndex({ created_at: -1 }, { partialFilterExpression: { status: { $in: ['new', 'paid'] } } })email_1
created_at_-1

Multikey: an index on an array field

At most one field of a compound index may be an array in any document; inserting a document with arrays in two indexed fields fails with cannot index parallel arrays.

db.products.createIndex({ tags: 1 })          // one entry per element

db.products.find({ tags: 'oak' })

Text, wildcard and hashed

db.articles.createIndex({ title: 'text', body: 'text' }, { weights: { title: 5 }, default_language: 'english' })
db.products.createIndex({ 'attrs.$**': 1 })        // any field under attrs

db.users.createIndex({ user_id: 'hashed' })        // for hashed shard keystitle_text_body_text
attrs.$**_1
user_id_hashed

Case insensitive index

db.users.createIndex({ name: 1 }, { collation: { locale: 'en', strength: 2 } })
db.users.find({ name: 'ANA POP' }).collation({ locale: 'en', strength: 2 })

Maintain

Hide an index before dropping it

Hiding is instant and reversible. Watch the slow query log for a few days; if nothing gets worse, drop the index.

db.orders.hideIndex('status_1')        // kept up to date, ignored by the planner

db.orders.unhideIndex('status_1'){ hidden_old: false, hidden_new: true, ok: 1 }
{ hidden_old: true, hidden_new: false, ok: 1 }

Which indexes are used

The counters reset when mongod restarts and are per member, so check every member and a long enough period before calling an index unused.

db.orders.aggregate([{ $indexStats: {} }, { $project: { name: 1, 'accesses.ops': 1, 'accesses.since': 1 } }])[
  { name: '_id_', accesses: { ops: Long('88210'), since: ISODate('2026-09-20T06:00:00.000Z') } },
  { name: 'status_1', accesses: { ops: Long('0'), since: ISODate('2026-09-20T06:00:00.000Z') } }
]

Index sizes

db.orders.stats({ indexDetails: false }).indexSizes
db.orders.totalIndexSize()

Explain & Tuning

Read explain()

executionStats runs the query and reports what it did

The three numbers to read are nReturned, totalKeysExamined and totalDocsExamined. When all three are close, the index fits the query; when docs examined is far above returned, the query reads documents only to throw them away.

db.orders.find({ status: 'paid' }).sort({ created_at: -1 }).explain('executionStats'){
  queryPlanner: {
    winningPlan: {
      stage: 'FETCH',
      inputStage: { stage: 'IXSCAN', keyPattern: { status: 1, created_at: -1 }, indexName: 'status_1_created_at_-1', direction: 'forward' }
    },
    rejectedPlans: []
  },
  executionStats: {
    nReturned: 311,
    executionTimeMillis: 2,
    totalKeysExamined: 311,
    totalDocsExamined: 311
  }
}

The stages you will see

StageMeaning
COLLSCANreads every document: no usable index
IXSCANwalks an index
FETCHreads the documents the index pointed to
SORTsorts in memory: the index does not match the sort
PROJECTION_COVEREDanswered from the index alone
EXPRESS_IXSCANfast path for simple equality on a unique index, 8.0+
SHARD_MERGEresults merged from several shards

Covered queries

When the filter and every projected field are in one index and _id is excluded, MongoDB answers from the index and never reads the documents, which is the fastest possible read.

db.users.createIndex({ email: 1, name: 1 })
db.users.find({ email: 'ana@example.com' }, { _id: 0, email: 1, name: 1 }).explain('executionStats').executionStats.totalDocsExamined0

Profiler and Running Operations

Log and profile slow operations

Level 1 writes slow operations into the capped system.profile collection of that database; level 2 records everything and costs noticeable performance. Operations slower than slowms are also written to the mongod log even with the profiler off.

db.setProfilingLevel(1, { slowms: 100 })          // profile operations slower than 100 ms

db.system.profile.find().sort({ ts: -1 }).limit(5).pretty()
db.system.profile.find({ planSummary: 'COLLSCAN' }, { ns: 1, millis: 1, command: 1 })
db.setProfilingLevel(0){ was: 0, slowms: 100, sampleRate: 1, ok: 1 }

What is running now, and stopping it

db.currentOp({ active: true, secs_running: { $gte: 5 } })
db.killOp(12345)
db.aggregate([{ $currentOp: { allUsers: true } }, { $match: { secs_running: { $gt: 10 } } }]){
  inprog: [
    { opid: 12345, active: true, secs_running: 41, op: 'command', ns: 'shop.orders', command: { aggregate: 'orders', pipeline: [ ... ] }, planSummary: 'COLLSCAN' }
  ],
  ok: 1
}

Query statistics per query shape

MongoDB 9.0+

From 9.0 $queryStats collects statistics by default for reads and writes, sampling a small share of operations, so the most expensive query shapes are visible without turning the profiler on.

db.getSiblingDB('admin').aggregate([
  { $queryStats: {} },
  { $sort: { 'metrics.totalExecMicros.sum': -1 } },
  { $limit: 10 }
])

Fix a Plan

Pin a plan or reject a query shape with query settings

MongoDB 8.0+

Query settings apply to every query with the same shape, from any client, without a code change, which makes them the way to fix a bad plan in production. They replace index filters.

db.adminCommand({
  setQuerySettings: { find: 'orders', filter: { status: 'paid' }, sort: { created_at: -1 }, $db: 'shop' },
  settings: { indexHints: { ns: { db: 'shop', coll: 'orders' }, allowedIndexes: ['status_1_created_at_-1'] } }
})
db.adminCommand({ setQuerySettings: querySettingsHash, settings: { reject: true } })
db.aggregate([{ $querySettings: {} }])

Query settings for one command only

MongoDB 9.0+

db.runCommand({
  find: 'orders',
  filter: { status: 'paid' },
  querySettings: { indexHints: { ns: { db: 'shop', coll: 'orders' }, allowedIndexes: [{ status: 1 }] } }
})

The plan cache

db.orders.getPlanCache().list()
db.orders.getPlanCache().clear()

Explain Modes

What each verbosity level runs

ModeRuns the queryShows
queryPlannernothe winning plan and the rejected plans
executionStatsyesplus counts and times for the winning plan
allPlansExecutionyesplus the trial results of every candidate plan

Schema Validation

$jsonSchema Validators

Create a collection with rules

db.createCollection('customers', {
  validator: { $jsonSchema: {
    bsonType: 'object',
    required: ['email', 'name', 'created_at'],
    properties: {
      email: { bsonType: 'string', pattern: '^[^@\\s]+@[^@\\s]+$' },
      name: { bsonType: 'string', minLength: 1, maxLength: 200 },
      tier: { enum: ['free', 'pro', 'enterprise'] },
      credits: { bsonType: ['int', 'long'], minimum: 0 },
      created_at: { bsonType: 'date' }
    }
  } },
  validationAction: 'error'
})

What a rejected write looks like

The error carries a details document with each rule that failed, so log errInfo in the application instead of just the message.

db.customers.insertOne({ email: 'not-an-email', name: 'Ana', created_at: new Date() })MongoServerError: Document failed validation
Additional information: {
  failingDocumentId: ObjectId('66f9a1c2e4b0d7a1c3f2e9c7'),
  details: {
    operatorName: '$jsonSchema',
    schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'email', details: [ { operatorName: 'pattern', specifiedAs: { pattern: '^[^@\\s]+@[^@\\s]+$' }, reason: 'regular expression did not match', consideredValue: 'not-an-email' } ] } ] } ]
  }
}

Levels and Actions

Add or change rules on an existing collection

db.runCommand({
  collMod: 'customers',
  validator: { $jsonSchema: { required: ['email'] } },
  validationLevel: 'moderate',
  validationAction: 'warn'
})
db.getCollectionInfos({ name: 'customers' })[0].options.validator

What each setting does

SettingValueEffect
validationLevelstrictcheck every insert and update (default)
validationLevelmoderateskip updates to documents that were already invalid
validationLevelconstraint9.0+, every document in the collection is guaranteed to satisfy the rules
validationLeveloffno validation
validationActionerrorreject the write (default)
validationActionwarnallow it, write a warning to the log
validationActionerrorAndLogreject it and log it, 8.1+

Find documents that break the current rules

db.customers.find({ $nor: [db.getCollectionInfos({ name: 'customers' })[0].options.validator] })

Bypass validation for a one off fix

The user needs the bypassDocumentValidation action, which dbAdmin and restore include. mongorestore has a --bypassDocumentValidation flag for the same reason: loading old data that predates the rules.

db.runCommand({ insert: 'customers', documents: [legacyDoc], bypassDocumentValidation: true })

Other Validation Tools

Validators with query operators

Query operators and $expr can express rules $jsonSchema cannot, such as one field being smaller than another. They can be combined with $jsonSchema inside $and.

db.runCommand({
  collMod: 'orders',
  validator: { $and: [
    { total: { $gte: 0 } },
    { status: { $in: ['new', 'paid', 'shipped', 'refunded', 'cancelled'] } },
    { $expr: { $lte: ['$discount', '$total'] } }
  ] }
}){ ok: 1 }

Check a collection's data files and indexes

validate checks storage and index consistency, not the schema rules. full: true reads every document and blocks writes to the collection while it runs, so run it on a secondary or in a quiet period.

db.orders.validate({ full: true }){
  ns: 'shop.orders',
  nInvalidDocuments: 0,
  nNonCompliantDocuments: 0,
  nrecords: 1204331,
  nIndexes: 5,
  valid: true,
  repaired: false,
  warnings: [],
  errors: [],
  ok: 1
}

Transactions

Run a Transaction

withTransaction commits, and retries on transient errors

Every operation inside the transaction must go through the session's database handle. An operation on the plain db variable runs outside the transaction and is committed at once, even if the transaction later aborts.

const session = db.getMongo().startSession()
session.withTransaction(() => {
  const s = session.getDatabase('shop')
  s.accounts.updateOne({ _id: 'A' }, { $inc: { balance: -100 } })
  s.accounts.updateOne({ _id: 'B' }, { $inc: { balance: 100 } })
  s.transfers.insertOne({ from: 'A', to: 'B', amount: 100, at: new Date() })
}, { readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } })
session.endSession()

The same in Node.js

const session = client.startSession()
try {
  await session.withTransaction(async () => {
    await accounts.updateOne({ _id: 'A' }, { $inc: { balance: -100 } }, { session })
    await accounts.updateOne({ _id: 'B' }, { $inc: { balance: 100 } }, { session })
  })
} finally {
  await session.endSession()
}

Manual control

Without withTransaction you have to retry yourself: retry the whole transaction on the TransientTransactionError label, and retry only the commit on UnknownTransactionCommitResult.

session.startTransaction({ readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } })
try {
  session.getDatabase('shop').orders.insertOne({ total: 50 })
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
  throw e
}

Limits and Good Practice

What to keep in mind

RuleDetail
Needs a replica set or sharded clustera single standalone mongod cannot run transactions
60 second default lifetimetransactionLifetimeLimitSeconds, then the server aborts it
Keep them smallabout 1000 modified documents is the usual guidance
Write conflicts abortthe second writer gets WriteConflict and must retry
DDLcreating collections and indexes inside is allowed since 4.4, dropping is not
Single document writes are already atomica transaction is only needed across documents

A cap on open transactions

MongoDB 9.0+

From 9.0 the server limits concurrent client transactions to 10000 by default and rejects more with TooManyOpenTransactions. Hitting it usually means transactions that are never committed or aborted.

db.adminCommand({ getParameter: 1, maxConcurrentMultiDocumentTransactions: 1 }){ maxConcurrentMultiDocumentTransactions: 10000, ok: 1 }

Retryable writes are on by default

Drivers retry a single write once after a network error or a failover, using a transaction number so the server applies it only once. updateMany and deleteMany are not retryable.

mongodb+srv://cluster0.example.net/shop?retryWrites=true&w=majority

Consistency Options

Causal consistency: read your own writes on secondaries

Inside a causally consistent session, a read waits until the member has applied the session's earlier writes, so a secondary read cannot miss them. It needs majority read and write concern to hold across failovers.

const s = db.getMongo().startSession({ causalConsistency: true })
const sdb = s.getDatabase('shop')
sdb.orders.insertOne({ _id: 9002, total: 75 })
sdb.orders.find({ _id: 9002 }).readPref('secondary').readConcern('majority')[ { _id: 9002, total: 75 } ]

A transaction in Python

with client.start_session() as session:
    def transfer(s):
        accounts = s.client.shop.accounts
        accounts.update_one({"_id": "A"}, {"$inc": {"balance": -100}}, session=s)
        accounts.update_one({"_id": "B"}, {"$inc": {"balance": 100}}, session=s)
    session.with_transaction(transfer)

Change Streams

Watch Changes

Watch a collection

Change streams read the oplog, so they need a replica set or sharded cluster. fullDocument: 'updateLookup' fetches the current document at the time the event is read, which can already include later changes.

const cs = db.orders.watch(
  [{ $match: { operationType: { $in: ['insert', 'update'] } } }],
  { fullDocument: 'updateLookup' }
)
while (cs.hasNext()) { printjson(cs.next()) }{
  _id: { _data: '8266F9A1C2000000012B042C0100296E5A1004' },
  operationType: 'update',
  clusterTime: Timestamp({ t: 1790678034, i: 1 }),
  wallTime: ISODate('2026-09-29T10:33:54.120Z'),
  ns: { db: 'shop', coll: 'orders' },
  documentKey: { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4') },
  updateDescription: { updatedFields: { status: 'shipped' }, removedFields: [], truncatedArrays: [] },
  fullDocument: { _id: ObjectId('66f9a1c2e4b0d7a1c3f2e9b4'), status: 'shipped', total: 129.9 }
}

Watch a database or the whole deployment

db.watch()
db.getMongo().watch([{ $match: { 'ns.coll': 'orders' } }])

Resume after a restart

A stream can resume only while its token is still in the oplog. If the consumer is down longer than the oplog window, the resume fails with ChangeStreamHistoryLost and you have to resynchronise from the collection.

const token = lastEvent._id                         // store it after handling each event

db.orders.watch([], { resumeAfter: token })
db.orders.watch([], { startAfter: token })          // also works after an invalidate event

db.orders.watch([], { startAtOperationTime: Timestamp({ t: 1790678034, i: 0 }) })

Pre and Post Images

The document before the change

Pre and post images are stored in a system collection and expire with the oplog, or earlier with expireAfterSeconds in changeStreamOptions. whenAvailable returns null when an image is gone; required fails the stream instead.

db.runCommand({ collMod: 'orders', changeStreamPreAndPostImages: { enabled: true } })
db.orders.watch([], { fullDocumentBeforeChange: 'whenAvailable', fullDocument: 'whenAvailable' })

Events larger than 16 MB

db.orders.watch([{ $changeStreamSplitLargeEvent: {} }], { fullDocument: 'updateLookup', fullDocumentBeforeChange: 'required' })

Event types

operationTypeWhen
insert, update, replace, deletedocument changes
drop, rename, dropDatabasethe collection or database went away
invalidatethe stream can no longer continue; resume with startAfter
create, createIndexes, modify, shardCollectionDDL events, with showExpandedEvents: true

Change Streams From Code

Node.js, with a stored resume token

Save the token after handling the event, not before, so a crash in between replays the event instead of losing it. Make the handler safe to run twice for the same event.

const stream = orders.watch([{ $match: { operationType: 'insert' } }], { resumeAfter: await loadToken() })
for await (const ev of stream) {
  await handle(ev.fullDocument)
  await saveToken(ev._id)
}

Time Series Collections

Create and Insert

A time series collection

MongoDB groups measurements with the same metaField value and close timestamps into compressed buckets, which cuts storage and index size many times over. Put the fields that identify a series in metaField and never a value that changes on every measurement.

db.createCollection('metrics', {
  timeseries: { timeField: 'ts', metaField: 'meta', granularity: 'minutes' },
  expireAfterSeconds: 60 * 60 * 24 * 90
})
db.metrics.insertMany([
  { ts: new Date(), meta: { host: 'web1', metric: 'cpu' }, value: 41.2 },
  { ts: new Date(), meta: { host: 'web2', metric: 'cpu' }, value: 17.9 }
])

Granularity or custom bucket spans

db.createCollection('ticks', { timeseries: { timeField: 't', metaField: 'sym', bucketMaxSpanSeconds: 300, bucketRoundingSeconds: 300 } })
db.runCommand({ collMod: 'metrics', timeseries: { granularity: 'hours' } })     // can only grow

Secondary indexes

db.metrics.createIndex({ 'meta.host': 1, ts: -1 })
db.metrics.createIndex({ ts: -1 })meta.host_1_ts_-1
ts_-1

Query

Downsample to five minute averages

db.metrics.aggregate([
  { $match: { 'meta.host': 'web1', ts: { $gte: ISODate('2026-09-29T00:00:00Z') } } },
  { $group: {
      _id: { $dateTrunc: { date: '$ts', unit: 'minute', binSize: 5 } },
      avg: { $avg: '$value' },
      max: { $max: '$value' }
  } },
  { $sort: { _id: 1 } }
])[
  { _id: ISODate('2026-09-29T00:00:00.000Z'), avg: 38.4, max: 52.1 },
  { _id: ISODate('2026-09-29T00:05:00.000Z'), avg: 36.9, max: 44.7 }
]

Storage in 9.0

MongoDB 9.0+

From 9.0 a time series collection is stored as a single namespace of compressed buckets rather than a view over a system.buckets collection, and it can be renamed. Upgrades of databases with thousands of time series collections take longer while they are converted.

db.adminCommand({ renameCollection: 'shop.metrics', to: 'shop.metrics_2026' })

When not to use one

// frequent updates to single measurements

// documents looked up one by one by _id

// data without a real time dimension

Latest Values and Archiving

The latest reading per series

db.metrics.aggregate([
  { $match: { ts: { $gte: new Date(Date.now() - 3600000) } } },
  { $group: { _id: '$meta.host', last: { $top: { sortBy: { ts: -1 }, output: { ts: '$ts', value: '$value' } } } } }
])[
  { _id: 'web1', last: { ts: ISODate('2026-09-29T11:41:00.000Z'), value: 41.2 } },
  { _id: 'web2', last: { ts: ISODate('2026-09-29T11:41:00.000Z'), value: 17.9 } }
]

Move cold data to cheaper storage with Online Archive

Atlas only

Online Archive moves documents older than the threshold to object storage and a federated endpoint queries both parts. It is an Atlas feature; self-managed deployments use TTL indexes plus exports instead.

atlas clusters onlineArchives create --clusterName Cluster0 --db shop --collection metrics \
  --dateField ts --archiveAfter 90

Users & Security

Turn On Authentication

Enable authorization, then create the first user through the localhost exception

With authorization on and no users, a connection from localhost may create the first user and nothing else. Create the admin user straight away; the exception closes as soon as one user exists.

# /etc/mongod.conf

security:
  authorization: enabled

mongosh --host 127.0.0.1                  # on the server itself, before any user exists

use admin
db.createUser({ user: 'root', pwd: passwordPrompt(), roles: ['root'] })

Log in

authSource is the database where the user was created, not the one you work in. Authentication failed with the right password is almost always a user created in admin and a connection string that authenticates against shop, or the other way round.

mongosh "mongodb://db1.internal/shop?authSource=admin" -u app
db.auth('app', passwordPrompt())          // inside an open shell

db.runCommand({ connectionStatus: 1 }).authInfo.authenticatedUsers[ { user: 'app', db: 'admin' } ]

Users and Roles

Create, change and remove users

use admin
db.createUser({ user: 'app', pwd: passwordPrompt(), roles: [{ role: 'readWrite', db: 'shop' }] })
db.grantRolesToUser('app', [{ role: 'read', db: 'reports' }])
db.revokeRolesFromUser('app', [{ role: 'read', db: 'reports' }])
db.changeUserPassword('app', passwordPrompt())
db.getUsers()
db.dropUser('old_app'){ ok: 1 }
...
[
  {
    _id: 'admin.app',
    userId: UUID('1f0c2b3a-4d5e-4f60-8a71-92b3c4d5e6f7'),
    user: 'app',
    db: 'admin',
    roles: [ { role: 'readWrite', db: 'shop' } ],
    mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
  }
]

Built-in roles

RoleGrants
read / readWriteread, or read and write, the collections of one database
dbAdminindexes, validation, stats; no data access
dbOwnerreadWrite plus dbAdmin plus userAdmin on one database
userAdmincreate users and roles in one database, which means it can grant itself anything there
clusterMonitorread only monitoring: serverStatus, currentOp, rs.status
clusterManager / clusterAdminreplication and sharding management
backup / restoremongodump and mongorestore
readAnyDatabase / readWriteAnyDatabaseevery database
rooteverything

A custom role with exact privileges

db.createRole({
  role: 'orders_writer',
  privileges: [{ resource: { db: 'shop', collection: 'orders' }, actions: ['find', 'insert', 'update'] }],
  roles: []
})
db.grantRolesToUser('app', ['orders_writer'])
db.getRole('orders_writer', { showPrivileges: true }){
  _id: 'admin.orders_writer',
  role: 'orders_writer',
  db: 'admin',
  privileges: [ { resource: { db: 'shop', collection: 'orders' }, actions: [ 'find', 'insert', 'update' ] } ],
  roles: [],
  isBuiltin: false
}

Encryption and Auditing

Require TLS

net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb.pem
    CAFile: /etc/ssl/ca.pem
    disabledProtocols: TLS1_0,TLS1_1

Encryption at rest with the WiredTiger encrypted storage engine

Enterprise only

Community Edition relies on disk or volume encryption from the operating system or cloud provider instead. Atlas encrypts storage by default.

mongod --enableEncryption --encryptionKeyFile /etc/mongodb/master.key --dbpath /var/lib/mongodb
# or KMIP: --kmipServerName kms.internal --kmipServerCAFile ca.pem

Auditing

Enterprise only

auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json
  filter: '{ atype: { $in: ["authenticate", "createUser", "dropCollection"] } }'

LDAP, Kerberos and OpenID Connect

Enterprise only

mongosh "mongodb://db1.internal/?authMechanism=PLAIN&authSource=$external" -u ana
mongosh "mongodb://db1.internal/?authMechanism=GSSAPI&authSource=$external" -u ana@EXAMPLE.COM
mongosh "mongodb://db1.internal/?authMechanism=MONGODB-OIDC"

Queryable Encryption: query fields the server cannot read

MongoDB 8.0+

Equality queries on encrypted fields are generally available since 7.0, range since 8.0, and prefix, suffix and substring since 9.0. Automatic encryption needs Enterprise or Atlas; Community can encrypt explicitly with the driver's encryption API. From 9.0 use the Automatic Encryption Shared Library, since mongocryptd is deprecated.

const encryptedFields = { fields: [
  { path: 'ssn', bsonType: 'string', queries: { queryType: 'equality' } },
  { path: 'salary', bsonType: 'int', queries: { queryType: 'range', min: 0, max: 1000000 } }
] }
// the driver encrypts before sending; the server stores and compares ciphertext

Hardening Checklist

Before a server faces a network

CheckHow
Authentication onsecurity.authorization: enabled
Listen only where needednet.bindIp, never 0.0.0.0 without a firewall
TLS onnet.tls.mode: requireTLS
One user per application, least privilegereadWrite on one database, not root
No server side JavaScript if unusedsecurity.javascriptEnabled: false
Patchedfollow the minor releases of your major version
Backups encrypted and testedrestore one regularly

Network and Log Protection

Allow an IP address on Atlas

Atlas only

Atlas refuses connections from addresses outside the project's access list, which is the usual cause of a server selection timeout from a new machine or CI runner.

atlas accessLists create 203.0.113.10 --type ipAddress --comment "office"
atlas accessLists list

Keep document contents out of the logs

Enterprise only

security:
  redactClientLogData: true

Replica Sets

Set Up

Start three members, then initiate once

A replica set needs a majority of voting members to elect a primary, so three members survive the loss of one. Two members cannot: when one fails, the other has no majority and steps down to secondary.

mongod --replSet rs0 --bind_ip localhost,db1.internal --dbpath /var/lib/mongodb --keyFile /etc/mongodb/keyfile
rs.initiate({
  _id: 'rs0',
  members: [
    { _id: 0, host: 'db1.internal:27017' },
    { _id: 1, host: 'db2.internal:27017' },
    { _id: 2, host: 'db3.internal:27017' }
  ]
})

Status

rs.status().members.map(m => ({ name: m.name, state: m.stateStr, health: m.health, lag: m.optimeDate }))[
  { name: 'db1.internal:27017', state: 'PRIMARY', health: 1, lag: ISODate('2026-09-29T10:40:02.000Z') },
  { name: 'db2.internal:27017', state: 'SECONDARY', health: 1, lag: ISODate('2026-09-29T10:40:02.000Z') },
  { name: 'db3.internal:27017', state: 'SECONDARY', health: 1, lag: ISODate('2026-09-29T10:40:01.000Z') }
]

Add, remove, step down

rs.add('db4.internal:27017')
rs.add({ host: 'db5.internal:27017', priority: 0, votes: 0 })
rs.remove('db4.internal:27017')
rs.stepDown(60)                       // primary steps down for 60 seconds, triggers an election

rs.freeze(120)                        // this secondary will not seek election for 120 seconds{ ok: 1 }

Member Options

Change priorities, hide a member, delay one

A hidden or delayed member must have priority 0. A delayed member gives you an hour to stop a bad deleteMany from reaching every copy, but it still votes, so give it votes: 0 if it would weaken write majority.

cfg = rs.conf()
cfg.members[0].priority = 2                      // preferred primary

cfg.members[2].priority = 0
cfg.members[2].hidden = true                     // invisible to clients: analytics, backups

cfg.members[2].secondaryDelaySecs = 3600         // one hour behind, protects against mistakes

rs.reconfig(cfg){ ok: 1 }

Member roles

MemberPriorityVotesServes readsUse
Normal secondary11yesfailover
Priority 001yesnever becomes primary, another data centre
Hidden00 or 1nobackups, reporting
Delayed00 or 1noundo window for bad writes
Arbiter01no dataavoid: breaks w: majority when a data member is down

Oplog and Lag

The oplog window and replication lag

The oplog window is how long a secondary can be offline and still catch up. If it falls further behind than the window, it needs a full initial sync, so size the oplog for your longest expected maintenance.

rs.printReplicationInfo()
rs.printSecondaryReplicationInfo()actual oplog size
'4096 MB'
---
configured oplog size
'4096 MB'
---
log length start to end
'187320 secs (52.03 hrs)'
---
oplog first event time
'Sat Sep 27 2026 06:39:12 GMT+0300'
---
oplog last event time
'Mon Sep 29 2026 10:41:12 GMT+0300'

Resize the oplog without a restart

db.adminCommand({ replSetResizeOplog: 1, size: 16384 })          // MB, run on each member

db.adminCommand({ replSetResizeOplog: 1, minRetentionHours: 72 })

Read preference

Secondary reads can return data that is seconds behind the primary, and they do not add write capacity. Use them for reports and analytics, not for reading back what the user just wrote.

db.orders.find().readPref('secondaryPreferred', [{ region: 'eu-west' }])
mongodb+srv://cluster0.example.net/shop?readPreference=secondaryPreferred&maxStalenessSeconds=120

Quick Checks

Who is primary, from any member

db.hello().primary
db.hello().isWritablePrimary
rs.status().members.find(m => m.stateStr === 'PRIMARY').namedb1.internal:27017
false
db1.internal:27017

Sharding

Shard a Collection

Pick the key, then shard

A good shard key has many distinct values, spreads writes evenly and appears in most queries. A key that only grows, such as a timestamp or an ObjectId, sends every insert to the same shard; hash it or put a high cardinality field in front.

sh.enableSharding('shop')                                             // optional in recent versions

db.orders.createIndex({ customer_id: 1, created_at: 1 })
sh.shardCollection('shop.orders', { customer_id: 1, created_at: 1 })   // ranged

sh.shardCollection('shop.events', { device_id: 'hashed' })             // hashed: even writes{ collectionsharded: 'shop.orders', ok: 1 }

Test a candidate key on real traffic

db.adminCommand({ analyzeShardKey: 'shop.orders', key: { customer_id: 1 }, keyCharacteristics: true, readWriteDistribution: true })
db.adminCommand({ configureQueryAnalyzer: 'shop.orders', mode: 'full', samplesPerSecond: 10 })

Where the data is

sh.status()
db.orders.getShardDistribution()
db.getSiblingDB('admin').aggregate([{ $shardedDataDistribution: {} }])Shard shard01 at shard01/s1a:27018,s1b:27018,s1c:27018
{ data: '41.2GiB', docs: 101482019, chunks: 331, 'estimated data per chunk': '127.45MiB', 'estimated docs per chunk': 306592 }
---
Shard shard02 at shard02/s2a:27018,s2b:27018,s2c:27018
{ data: '40.8GiB', docs: 100297180, chunks: 327, 'estimated data per chunk': '127.76MiB', 'estimated docs per chunk': 306719 }
---
Totals
{ data: '82GiB', docs: 201779199, chunks: 658 }

Change the Layout

Change the shard key online

MongoDB 8.0+

Resharding copies the whole collection to its new layout while writes continue, so it needs free disk for a second copy and takes hours on large collections. forceRedistribution, from 8.0, uses the same process to rebalance with the current key, for example after adding shards.

db.adminCommand({ reshardCollection: 'shop.orders', key: { customer_id: 'hashed' } })
db.adminCommand({ refineCollectionShardKey: 'shop.orders', key: { customer_id: 1, created_at: 1, _id: 1 } })   // add suffix fields

db.adminCommand({ reshardCollection: 'shop.orders', key: { customer_id: 1 }, forceRedistribution: true })       // same key, spread again

Move or unshard a whole collection

MongoDB 8.0+

db.adminCommand({ moveCollection: 'shop.audit', toShard: 'shard02' })
db.adminCommand({ unshardCollection: 'shop.logs', toShard: 'shard01' })

The balancer

sh.getBalancerState()
sh.stopBalancer()                  // before a manual backup of the cluster

sh.startBalancer()
db.getSiblingDB('config').settings.updateOne(
  { _id: 'balancer' },
  { $set: { activeWindow: { start: '01:00', stop: '05:00' } } },
  { upsert: true }
)

Remove a shard with the draining commands

MongoDB 8.3+

These replace the single removeShard command, deprecated in 8.3, with steps you can check and stop. Databases whose primary shard is the one being drained still need movePrimary before the commit.

db.adminCommand({ startShardDraining: 'shard03' })
db.adminCommand({ shardDrainingStatus: 'shard03' })
db.adminCommand({ commitShardRemoval: 'shard03' })

Queries on a Sharded Cluster

Targeted versus scatter gather

Queries that include the shard key prefix go to the shards that own that range; the rest are broadcast to every shard and merged on mongos. A handful of broadcast queries is fine; making them the main workload removes most of the benefit of sharding.

db.orders.find({ customer_id: cid })            // goes to one shard

db.orders.find({ status: 'paid' })              // asks every shard

db.orders.find({ status: 'paid' }).explain().queryPlanner.winningPlan.stageSHARD_MERGE

Zones

Keep EU customers on EU shards

The balancer moves chunks so each zone's key range lives only on the shards in that zone, which is how data residency rules are met inside one cluster.

sh.addShardToZone('shard-eu-1', 'EU')
sh.addShardToZone('shard-us-1', 'US')
sh.shardCollection('shop.customers', { region: 1, _id: 1 })
sh.updateZoneKeyRange('shop.customers', { region: 'EU', _id: MinKey() }, { region: 'EU', _id: MaxKey() }, 'EU')
sh.updateZoneKeyRange('shop.customers', { region: 'US', _id: MinKey() }, { region: 'US', _id: MaxKey() }, 'US')

Backup & Restore

mongodump and mongorestore

Dump and restore one database

mongodump reads documents through the normal query path and mongorestore rebuilds every index at the end, so both are slow for hundreds of gigabytes. Past that size, use snapshots or a managed backup with point in time recovery.

mongodump --uri="$MONGODB_URI" --db=shop --gzip --archive=shop-2026-09-29.archive.gz
mongorestore --uri="$RESTORE_URI" --gzip --archive=shop-2026-09-29.archive.gz --nsInclude='shop.*'2026-09-29T11:02:11.482+0300	writing shop.orders to archive 'shop-2026-09-29.archive.gz'
2026-09-29T11:02:11.483+0300	writing shop.customers to archive 'shop-2026-09-29.archive.gz'
2026-09-29T11:02:44.901+0300	done dumping shop.orders (1204331 documents)
2026-09-29T11:02:45.019+0300	done dumping shop.customers (88213 documents)

One collection, a subset, or into another database

mongodump --uri="$MONGODB_URI" --db=shop --collection=orders --query='{"status":"paid"}' --out=dump/
mongorestore --uri="$MONGODB_URI" --nsFrom='shop.*' --nsTo='shop_copy.*' dump/
mongorestore --uri="$MONGODB_URI" --drop --nsInclude='shop.orders' dump/2026-09-29T11:24:40.011+0300	preparing collections to restore from
2026-09-29T11:24:40.052+0300	restoring shop_copy.orders from dump/shop/orders.bson
2026-09-29T11:24:41.390+0300	finished restoring shop_copy.orders (311 documents, 0 failures)
2026-09-29T11:24:41.390+0300	311 document(s) restored successfully. 0 document(s) failed to restore.

Consistent dump of a running replica set

Without --oplog, documents changed during a long dump are captured at different moments. --oplog records the writes made while dumping and --oplogReplay applies them, so the restore is consistent to the end of the dump. It works only for a full deployment dump.

mongodump --uri="$MONGODB_URI" --oplog --gzip --archive=full.archive.gz
mongorestore --uri="$RESTORE_URI" --oplogReplay --gzip --archive=full.archive.gz

Export and Import

mongoexport to JSON or CSV

mongoexport writes Extended JSON, and CSV loses types entirely, so it is for moving data to other tools, not for backups. Use mongodump, which keeps BSON types exactly.

mongoexport --uri="$MONGODB_URI" --collection=orders --query='{"status":"paid"}' --out=paid.json
mongoexport --uri="$MONGODB_URI" --collection=orders --type=csv --fields=_id,status,total,created_at --out=orders.csv
mongoexport --uri="$MONGODB_URI" --collection=orders --jsonArray --pretty --limit=52026-09-29T11:20:02.118+0300	connected to: mongodb+srv://[**REDACTED**]@cluster0.example.net/shop
2026-09-29T11:20:02.904+0300	exported 311 records

Inspect a BSON file

bsondump dump/shop/orders.bson | head -n 3
bsondump --type=debug dump/shop/orders.bson

Snapshots and Point in Time

Filesystem snapshot of a member

With journaling on and the journal on the same volume, a snapshot is consistent even without fsyncLock. Take it from a hidden secondary so the primary never blocks.

db.fsyncLock()          // flush and block writes on this member

// take the LVM, EBS or ZFS snapshot here

db.fsyncUnlock()

Managed backups with point in time restore

Atlas only

atlas backups snapshots list Cluster0
atlas backups restores start pointInTime --clusterName Cluster0 --pointInTimeUTCSeconds 1790678034 --targetClusterName Cluster0-restore

Choosing a method

MethodGood forPoint in time
mongodump / mongorestoresmall databases, moving dataonly to the end of the dump
Filesystem snapshotslarge self-managed deploymentsno, plus oplog replay by hand
Ops Manager or Cloud ManagerEnterprise deploymentsyes
Atlas cloud backupAtlas clustersyes, with continuous backup
Percona Backup for MongoDBopen source alternativeyes

Copy Between Clusters

Stream a collection from one cluster to another, with no file in between

Both tools read and write the archive format on standard input and output, so the copy needs no disk space in between. For continuous copies between clusters, look at mongosync or Cluster-to-Cluster Sync instead.

mongodump --uri="$SOURCE_URI" --db=shop --collection=orders --archive | \
  mongorestore --uri="$TARGET_URI" --archive --nsInclude='shop.orders' --drop

Monitoring

Server Health

Connections and operation counters

Hundreds of connections usually mean each request opens its own client, or too many application instances with large pools. One MongoClient per process, reused for every request, is the fix in almost every driver.

db.serverStatus().connections
db.serverStatus().opcounters{ current: 184, available: 838676, totalCreated: 90412, active: 12, threaded: 184, rejected: 0 }
{ insert: Long('8812034'), query: Long('41290117'), update: Long('6620481'), delete: Long('301224'), getmore: Long('882013'), command: Long('90210334') }

The WiredTiger cache

Cache use near the maximum is normal. Watch the dirty share: above about 20% of the cache, application threads start doing eviction work themselves and every operation slows down.

const c = db.serverStatus().wiredTiger.cache
({ usedGB: c['bytes currently in the cache'] / 2 ** 30, maxGB: c['maximum bytes configured'] / 2 ** 30, dirtyGB: c['tracked dirty bytes in the cache'] / 2 ** 30 }){ usedGB: 6.12, maxGB: 7.5, dirtyGB: 0.31 }

Latency per collection

db.orders.aggregate([{ $collStats: { latencyStats: { histograms: false } } }]).next().latencyStats
db.adminCommand({ top: 1 }).totals['shop.orders']{
  reads: { latency: Long('88213042'), ops: Long('412331'), queryableEncryptionLatencyMicros: Long('0') },
  writes: { latency: Long('20411023'), ops: Long('90881'), queryableEncryptionLatencyMicros: Long('0') },
  commands: { latency: Long('1210'), ops: Long('12') },
  transactions: { latency: Long('0'), ops: Long('0') }
}

Command Line Tools

mongostat and mongotop

mongostat --uri="$MONGODB_URI" 5                 # every 5 seconds

mongotop --uri="$MONGODB_URI" 10                 # time spent per collectioninsert query update delete getmore command dirty  used flushes vsize   res qrw arw net_in net_out conn    set repl                time
    22   410     31      2      18   120|0  1.1% 81.6%       0 12.2G 7.60G 0|0 1|0   402k   3.11m  184    rs0  PRI Sep 29 11:20:05.118

Logs from inside the shell

Since 4.4 the log is structured JSON, one object per line, so jq is the fastest way to filter it: jq 'select(.attr.durationMillis > 500)' mongod.log lists every slow operation.

db.adminCommand({ getLog: 'global' }).log.slice(-5)
db.adminCommand({ getLog: 'startupWarnings' })
db.adminCommand({ setParameter: 1, logLevel: 1 })[
  '{"t":{"$date":"2026-09-29T11:30:02.118+03:00"},"s":"I","c":"COMMAND","id":51803,"ctx":"conn412","msg":"Slow query","attr":{"ns":"shop.orders","planSummary":"COLLSCAN","durationMillis":912}}',
  ...
]

What to alert on

MetricAlert when
Replication lagabove a few seconds for minutes
Oplog windowbelow the longest planned maintenance
Connectionsclose to the limit, or climbing steadily
Cache dirty shareabove 20%
Queued readers and writersgrowing, from serverStatus().queues
Disk freebelow the size of the largest collection plus its indexes
Page faults and swapany sustained swap use

Sizes and Managed Metrics

Every database with its size, largest first

db.adminCommand({ listDatabases: 1 }).databases
  .sort((a, b) => b.sizeOnDisk - a.sizeOnDisk)
  .map(d => `${d.name}: ${(d.sizeOnDisk / 2 ** 30).toFixed(2)} GiB`)[ 'shop: 1.84 GiB', 'reports: 0.42 GiB', 'local: 0.21 GiB', 'config: 0.00 GiB', 'admin: 0.00 GiB' ]

Atlas metrics from the command line

Atlas only

atlas processes list
atlas metrics processes cluster0-shard-00-00.example.net:27017 --granularity PT1M --period PT1H --type CONNECTIONS,OPCOUNTER_QUERY

Config & Upgrades

Configuration

Read the running configuration

db.adminCommand({ getCmdLineOpts: 1 }).parsed
db.adminCommand({ getParameter: '*' })
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 }){ featureCompatibilityVersion: { version: '8.0' }, ok: 1 }

Change a parameter at runtime

setParameter changes are lost on restart. Put anything permanent under setParameter in mongod.conf as well.

db.adminCommand({ setParameter: 1, cursorTimeoutMillis: 1200000 })
db.adminCommand({ setParameter: 1, transactionLifetimeLimitSeconds: 120 }){ was: 600000, ok: 1 }
{ was: 60, ok: 1 }

Production settings on Linux

8.0 moved to a newer TCMalloc that uses per CPU caches and works best with Transparent Huge Pages on, reversing the advice for 7.0 and earlier. Check the startup warnings after changing it.

# XFS for the data directory, noatime

# ulimit -n 64000 and ulimit -u 64000 for the mongod user (the packaged systemd unit sets them)

# 8.0 and newer: Transparent Huge Pages enabled (always); earlier versions: disabled

# vm.swappiness = 1, and NTP or chrony on every member

Upgrades

Rolling upgrade of a replica set

Until you raise the FCV, the new binaries keep the old data format and you can still go back to the previous version. Raise it only after the application has run on the new version for a while, because downgrading afterwards is much harder.

# 1. upgrade each secondary: stop mongod, install the new binaries, start, wait for SECONDARY

# 2. step down the primary, then upgrade it the same way

rs.stepDown()
# 3. when every member runs the new version and the application works:

db.adminCommand({ setFeatureCompatibilityVersion: '9.0', confirm: true }){ ok: 1 }

Upgrade paths

FromToPath
6.08.06.0 to 7.0 to 8.0, one major at a time
7.08.0direct
7.09.07.0 to 8.0 to 9.0
8.09.0direct
Driversanyupgrade drivers first; check the compatibility table

Stable API: keep code working across upgrades

With strict set, the server rejects commands outside Stable API version 1, so code that passes today keeps its behaviour on later server versions.

const client = new MongoClient(uri, { serverApi: { version: '1', strict: true, deprecationErrors: true } })

Service and Logs

Control the service on Linux

sudo systemctl start mongod
sudo systemctl restart mongod
sudo systemctl status mongod
journalctl -u mongod --since "10 min ago"
tail -f /var/log/mongodb/mongod.log | jq -c 'select(.s == "W" or .s == "E")'

Rotate the log

db.adminCommand({ logRotate: 1 })
# mongod.conf, when logrotate moves the file:

systemLog:
  logRotate: reopen{ ok: 1 }

Change an Atlas cluster tier without downtime

Atlas only

atlas clusters update Cluster0 --tier M30
atlas clusters watch Cluster0

The in-memory storage engine

Enterprise only

Data lives only in RAM, which gives predictable latency and loses everything on restart unless another replica set member persists it.

storage:
  engine: inMemory
  inMemory:
    engineConfig:
      inMemorySizeGB: 8

MongoDB From Code

Connect and Query

The official driver

Node.js

Create the client once when the process starts and share it. Each MongoClient holds its own pool, so a new client per request opens new connections and runs the TLS and authentication handshake every time.

import { MongoClient, ObjectId } from 'mongodb'

const client = new MongoClient(process.env.MONGODB_URI, { maxPoolSize: 50 })
const orders = client.db('shop').collection('orders')

const recent = await orders.find({ status: 'paid' }).sort({ created_at: -1 }).limit(20).toArray()
const one = await orders.findOne({ _id: new ObjectId(req.params.id) })
await orders.updateOne({ _id: one._id }, { $set: { status: 'shipped' } })

Mongoose

Node.js

import mongoose from 'mongoose'
await mongoose.connect(process.env.MONGODB_URI)
const Order = mongoose.model('Order', new mongoose.Schema({
  status: { type: String, enum: ['new', 'paid', 'shipped'], index: true },
  total: Number
}, { timestamps: true }))
const paid = await Order.find({ status: 'paid' }).sort({ createdAt: -1 }).limit(20).lean()

PyMongo, with the async client

Python

PyMongo has a native asyncio client, AsyncMongoClient, which replaces Motor for new async code. Motor is deprecated.

import os
from bson import ObjectId
from pymongo import MongoClient, AsyncMongoClient

client = MongoClient(os.environ["MONGODB_URI"])
orders = client.shop.orders
recent = list(orders.find({"status": "paid"}).sort("created_at", -1).limit(20))
one = orders.find_one({"_id": ObjectId(order_id)})

aclient = AsyncMongoClient(os.environ["MONGODB_URI"])
doc = await aclient.shop.orders.find_one({"status": "new"})

Go driver v2

Go

client, err := mongo.Connect(options.Client().ApplyURI(os.Getenv("MONGODB_URI")))
if err != nil { log.Fatal(err) }
defer client.Disconnect(context.Background())

orders := client.Database("shop").Collection("orders")
opts := options.Find().SetSort(bson.D{{Key: "created_at", Value: -1}}).SetLimit(20)
cur, err := orders.Find(ctx, bson.D{{Key: "status", Value: "paid"}}, opts)
var recent []Order
err = cur.All(ctx, &recent)

Java sync driver

Java

MongoClient client = MongoClients.create(System.getenv("MONGODB_URI"));
MongoCollection<Document> orders = client.getDatabase("shop").getCollection("orders");
List<Document> recent = orders.find(Filters.eq("status", "paid"))
    .sort(Sorts.descending("created_at"))
    .limit(20)
    .into(new ArrayList<>());
orders.updateOne(Filters.eq("_id", new ObjectId(id)), Updates.set("status", "shipped"));

C# driver with typed models

C#

var client = new MongoClient(Environment.GetEnvironmentVariable("MONGODB_URI"));
var orders = client.GetDatabase("shop").GetCollection<Order>("orders");
var recent = await orders.Find(o => o.Status == "paid")
    .SortByDescending(o => o.CreatedAt)
    .Limit(20)
    .ToListAsync();
await orders.UpdateOneAsync(o => o.Id == id, Builders<Order>.Update.Set(o => o.Status, "shipped"));

Driver Habits

ObjectId from a string, safely

A 24 character hex string and an ObjectId are different types, so findOne({ _id: '66f9...' }) finds nothing. Validate and convert at the edge of the application.

// Node.js

if (!ObjectId.isValid(id)) return res.status(400).end()
const doc = await orders.findOne({ _id: ObjectId.createFromHexString(id) })

Never build filters from raw request bodies

If a request body is passed straight into a filter, a client can send operators instead of values. Cast inputs to the expected type, or validate them with a schema, before they reach a query.

// { "email": { "$ne": null } } in a login body would match any user

const email = String(req.body.email)
const user = await users.findOne({ email })

Pool and timeout options in the connection string

timeoutMS sets one overall deadline for each operation, including retries, in current drivers. serverSelectionTimeoutMS decides how fast the application reports that no server is reachable, 30 seconds by default.

mongodb+srv://cluster0.example.net/shop?maxPoolSize=50&minPoolSize=5&maxIdleTimeMS=60000&serverSelectionTimeoutMS=5000&timeoutMS=10000

Serverless and Short Lived Processes

Reuse the client across function invocations

A module level client survives between warm invocations, so each call skips the connection handshake. Keep the pool small, because every concurrent function instance opens its own connections.

let clientPromise
export async function handler(event) {
  clientPromise ??= new MongoClient(process.env.MONGODB_URI, { maxPoolSize: 5 }).connect()
  const client = await clientPromise
  return client.db('shop').collection('orders').findOne({ _id: event.id })
}

Error Codes

Server Error Codes

Codes to handle in application code

CodeNameUsual cause and fix
11000DuplicateKeya unique index rejected the value; return a conflict or update instead
121DocumentValidationFailurethe document breaks the collection validator; read errInfo
13Unauthorizedthe user lacks a role for this action or database
18AuthenticationFailedwrong password or wrong authSource
50MaxTimeMSExpiredthe operation hit maxTimeMS; add an index or raise the limit
112WriteConflicttwo transactions wrote the same document; retry the transaction
251NoSuchTransactionthe transaction was aborted or timed out, often after 60 seconds
10107NotWritablePrimarya write reached a secondary after a failover; the driver retries
189PrimarySteppedDownan election is in progress; retryable
146ExceededMemoryLimitthe operation passed the 9.0 per operation memory limit
292QueryExceededMemoryLimitNoDiskUseAlloweda sort or group needed disk with allowDiskUse off
10334BSONObjectTooLargea document or an upsert result would exceed 16 MiB
286ChangeStreamHistoryLostthe resume token fell out of the oplog
26NamespaceNotFoundthe collection or database does not exist
85 / 86IndexOptionsConflict / IndexKeySpecsConflictan index with that key or name already exists with other options

Catch duplicates in Node.js

try {
  await users.insertOne({ email })
} catch (e) {
  if (e.code === 11000) return res.status(409).json({ error: 'email already registered' })
  throw e
}

Connection Errors

The messages and what they mean

MessageCause
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017mongod is not running, or listens on another address
querySrv ENOTFOUND _mongodb._tcp.cluster0...DNS cannot resolve the SRV record: check the host name or the DNS server
bad auth : authentication failedAtlas user or password is wrong, or the password needs percent encoding
Server selection timed out after 30000 msfirewall, IP access list, or wrong replica set name
connection <monitor> to ... closedTLS mismatch or a proxy cutting idle connections
not primary and secondaryOk=falsea direct connection to a secondary; add the replica set to the URI

Diagnose from the client machine

Walk down the layers: DNS for mongodb+srv, then TCP to port 27017, then TLS, then authentication. Most connection errors stop at the first two.

mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"
nslookup -type=SRV _mongodb._tcp.cluster0.example.net
nc -vz db1.internal 27017
curl -s https://checkip.amazonaws.com          # the public IP to add to the Atlas access list{ ok: 1 }
_mongodb._tcp.cluster0.example.net	service = 0 0 27017 cluster0-shard-00-00.example.net.
Connection to db1.internal port 27017 [tcp/*] succeeded!
203.0.113.10

More Errors and Their Fixes

Sort without an index on a large result

Either index the sort field, which removes the in-memory sort entirely, or allow the sort to spill to disk. The index is almost always the better fix.

db.orders.find().sort({ note: 1 }).allowDiskUse(false)MongoServerError: Executor error during find command :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting.

Cursor timed out in a long loop

An idle cursor is closed after 10 minutes by default (cursorTimeoutMillis). Process in batches with keyset pagination, or read the ids first, instead of holding one cursor through slow work.

db.orders.find().forEach(d => slowWork(d))MongoServerError: cursor id 7291841029312 not found

Write concern not satisfied in time

The write succeeded on the primary but not enough members confirmed it within wtimeout, so it is not rolled back, only unconfirmed. Check replication lag and member health rather than retrying the write blindly.

db.orders.insertOne({ total: 10 }, { writeConcern: { w: 'majority', wtimeout: 2000 } })MongoWriteConcernError: waiting for replication timed out

Retry a transaction in Python

from pymongo.errors import PyMongoError
try:
    session.with_transaction(transfer)
except PyMongoError as e:
    if e.has_error_label("TransientTransactionError"):
        pass  # with_transaction already retried for 120 seconds; alert or queue the work

    raise

Versions & SQL

Release Support

Versions and end of life, as of September 29, 2026

Major versions get about five years of support. Minor releases such as 8.1, 8.2 and 8.3 reach Atlas first and self-managed deployments only in some cases; most self-managed servers should run the latest major.

VersionTypeReleasedEnd of life
9.0majorSeptember 2026October 31, 2031
8.3minor releaseMay 4, 2026October 31, 2029
8.2minor release2025ended July 31, 2026
8.0majorOctober 2024October 31, 2029
7.0majorAugust 2023August 31, 2027
6.0majorJuly 2022ended July 31, 2025

What each recent version added

VersionHighlights
7.0compound wildcard indexes, $median and $percentile, Queryable Encryption equality GA, analyzeShardKey
8.0faster reads and writes, express query path, bulkWrite across collections, query settings, sort option on updateOne, QE range queries, moveCollection and unshardCollection, defaultMaxTimeMS
8.3$scoreFusion GA, $$IDX and arrayIndexAs, $convert base, $toArray and $toObject, $hash and $hexHash, $createObjectId, cost based ranker by default, shard draining commands
9.0$where, $function and $accumulator back on WebAssembly, per operation memory limit, cap on open transactions, querySettings per command, constraint validation level, QE prefix, suffix and substring GA, single namespace time series, $queryStats on by default, null semantics on dotted paths

SQL to MongoDB

Terms

SQLMongoDB
databasedatabase
tablecollection
rowdocument
columnfield
primary key_id
indexindex
JOIN$lookup, or an embedded document
GROUP BY$group
viewview
transactiontransaction, with a session

The same statements side by side

The SQL to MongoDB button in the toolbox converts whole statements, including joins, GROUP BY with HAVING and INSERT with several rows, and lists what to check by hand.

SQLMongoDB
SELECT * FROM users WHERE age > 30 ORDER BY name LIMIT 10db.users.find({ age: { $gt: 30 } }).sort({ name: 1 }).limit(10)
SELECT name, email FROM usersdb.users.find({}, { name: 1, email: 1, _id: 0 })
SELECT COUNT(*) FROM users WHERE activedb.users.countDocuments({ active: true })
INSERT INTO users (name) VALUES ('Ana')db.users.insertOne({ name: 'Ana' })
UPDATE users SET plan = 'pro' WHERE id = 7db.users.updateOne({ _id: 7 }, { $set: { plan: 'pro' } })
DELETE FROM users WHERE active = falsedb.users.deleteMany({ active: false })
SELECT country, COUNT(*) FROM users GROUP BY countrydb.users.aggregate([{ $group: { _id: '$country', n: { $sum: 1 } } }])
WHERE name LIKE 'An%'{ name: /^An/ }
WHERE email IS NULL{ email: null }
CREATE INDEX ON users (email)db.users.createIndex({ email: 1 })

MongoDB or a relational database

QuestionMongoDBPostgreSQL or MySQL
Data shapenested documents that vary per recordtables with a fixed schema
Relationsembedded or referenced, joins with $lookupforeign keys and joins everywhere
Schema changesadd fields as you go, validate with $jsonSchemamigrations with ALTER TABLE
Scaling writesbuilt in shardingreplicas, partitioning, external sharding
Transactionsmulti document, best kept smallthe default way of working
Ad hoc reportingaggregation pipelineSQL, the widest tool support

Checking and Changing Versions

Server, shell and FCV versions

db.version()
version()
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 }).featureCompatibilityVersion.version8.0.32
2.5.8
8.0

Removed, deprecated and replaced

FeatureStatusUse instead
legacy mongo shellremoved in 6.0mongosh
count(), insert(), update(), remove()deprecated in drivers and mongoshcountDocuments(), insertOne(), updateOne(), deleteMany()
index filtersdeprecated since 8.0query settings
removeSharddeprecated in 8.3startShardDraining and commitShardRemoval
mongocryptddeprecated in 9.0the Automatic Encryption Shared Library
$where, $function, $accumulatordeprecated in 8.0, re-enabled in 9.0$expr when possible
net.wireObjectCheckdeprecated in 9.0BSON is validated by default
Motor for PythondeprecatedAsyncMongoClient in PyMongo

The same JSON query in MongoDB and PostgreSQL

TaskMongoDBPostgreSQL jsonb
Field equals{ 'meta.tier': 'gold' }meta ->> 'tier' = 'gold'
Contains{ tags: 'oak' }tags @> '["oak"]'
Field exists{ phone: { $exists: true } }meta ? 'phone'
Index itcreateIndex({ 'meta.tier': 1 })CREATE INDEX ON t ((meta ->> 'tier'))
Set a field$set: { 'meta.tier': 'pro' }jsonb_set(meta, '{tier}', '"pro"')

What Is a MongoDB Cheat Sheet

A MongoDB cheat sheet is a one page reference to the mongosh commands, query and update operators, aggregation stages and administration tasks of the MongoDB database, laid out so you can find the right syntax in seconds instead of searching the manual. People also call it a mongosh cheat sheet or a Mongo shell cheat sheet, and they mean the same mix of shell commands, queries and pipelines.

This MongoDB cheat sheet covers 30 sections and 276 snippets for MongoDB 7.0, 8.0, 8.3 and 9.0. Every snippet that needs a newer release names the version that added it, and the server version picker next to the search box hides everything your server cannot run. Rows that need Enterprise Advanced or Atlas say so under their title. Each card holds copyable examples with a one line description, the output mongosh prints where it helps, and a short explanation of why MongoDB behaves that way.

The query toolbox at the top formats and minifies mongosh code, lints queries and pipelines for common mistakes, converts SQL statements into find and aggregate calls, reads explain() output in plain words and suggests an index, converts between mongosh syntax and Extended JSON, rewrites mongosh calls as PyMongo code, and turns CSV or JSON into insertMany calls. The command builders write mongodump and mongorestore commands, connection strings, users with the right roles, indexes that follow the ESR rule and a starting mongod.conf. None of it sends anything to a server.

How It Differs From the Documentation

The MongoDB manual is thorough and spread across hundreds of pages. This page shows the shortest working form of each command next to the mistake that usually comes with it. For the SQL side of the same ideas, see the SQL cheat sheet; for a relational database with strong JSON support, the PostgreSQL cheat sheet.


What This MongoDB Cheat Sheet Covers

The 30 sections follow the life of a database, from the first connection to running it in production, and each link jumps to that section above.


MongoDB Commands List

The commands people look up most often, one line each. The sections above show each of them with options, output and the mistakes that come with them.

TaskCommand
Connect with mongoshmongosh "mongodb+srv://cluster0.example.net/shop" -u app
Show the server versiondb.version()
List databasesshow dbs
Switch databaseuse shop
List collectionsshow collections
Create a collectiondb.createCollection('orders')
Delete a collectiondb.orders.drop()
Delete a databasedb.dropDatabase()
Insert a documentdb.orders.insertOne({ status: 'new', total: 40 })
Insert many documentsdb.orders.insertMany([{ ... }, { ... }])
Find documentsdb.orders.find({ status: 'paid' })
Find one documentdb.orders.findOne({ _id: ObjectId('...') })
Choose fieldsdb.orders.find({}, { total: 1, _id: 0 })
Sort and limitdb.orders.find().sort({ created_at: -1 }).limit(10)
Count documentsdb.orders.countDocuments({ status: 'paid' })
Distinct valuesdb.orders.distinct('status')
Update one fielddb.orders.updateOne({ _id: id }, { $set: { status: 'shipped' } })
Update many documentsdb.orders.updateMany({ status: 'new' }, { $set: { status: 'expired' } })
Insert or updatedb.visits.updateOne({ page }, { $inc: { n: 1 } }, { upsert: true })
Add to an arraydb.posts.updateOne({ _id: 1 }, { $push: { tags: 'db' } })
Delete documentsdb.sessions.deleteMany({ expires_at: { $lt: new Date() } })
Group and countdb.orders.aggregate([{ $group: { _id: '$status', n: { $sum: 1 } } }])
Join two collections{ $lookup: { from: 'customers', localField: 'customer_id', foreignField: '_id', as: 'customer' } }
Create an indexdb.orders.createIndex({ customer_id: 1, created_at: -1 })
List indexesdb.orders.getIndexes()
See a query plandb.orders.find({ ... }).explain('executionStats')
Create a userdb.createUser({ user: 'app', pwd: passwordPrompt(), roles: ['readWrite'] })
Replica set statusrs.status()
Sharding statussh.status()
Running operationsdb.currentOp({ active: true })
Back up a databasemongodump --uri="$URI" --db=shop --gzip --archive=shop.gz
Restore a backupmongorestore --uri="$URI" --gzip --archive=shop.gz
Export to CSVmongoexport --collection=orders --type=csv --fields=_id,total --out=o.csv
Leave mongoshexit

mongosh Cheat Sheet

mongosh is the MongoDB Shell, a Node.js based REPL that replaced the legacy mongo shell. Besides every JavaScript expression, it understands these helpers.

HelperWhat it does
help, db.help(), db.orders.help()help at each level
show dbs, show collections, show users, show roleslist objects
use nameswitch database
itthe next batch of a cursor
db.getSiblingDB('admin')another database without switching
db.getCollection('a-b')a collection whose name is not a valid identifier
printjson(x), EJSON.stringify(x)print a value, or as Extended JSON
load('file.js')run a script in the current shell
passwordPrompt()ask for a password without echoing it
config.set('editor', 'vim'), edit xedit a variable in an external editor
sleep(ms)pause a script
rs.*, sh.*replica set and sharding helpers
exit, quit()leave

What MongoDB Is

MongoDB is a document database: instead of rows in tables, it stores records as documents, JSON like objects saved in a binary format called BSON, grouped into collections. A document can hold nested objects and arrays, and documents in the same collection do not need the same fields, so the shape of the data can follow the shape of the objects in your code.

It was first released in 2009 by 10gen, the company now called MongoDB, Inc. The server is source available under the Server Side Public License; Community Edition is free, Enterprise Advanced adds features such as LDAP, auditing and encryption at rest, and Atlas is the managed cloud service. MongoDB 8.0 arrived in October 2024, and MongoDB 9.0 was released in September 2026.

Its strengths are a flexible schema, a query language that works naturally with nested data, built in replication with automatic failover, and horizontal scaling through sharding. The aggregation pipeline, change streams, time series collections, and full text and vector search cover much of what used to need separate systems.

Where It Fits

MongoDB suits product catalogues, content, user profiles, event and IoT data, mobile and web back ends and other workloads where records vary in shape and are read as a whole. It is a common choice for a cloud-based app and for microservices that each own their data. For heavily relational data with many joins and ad hoc reporting, a relational database is usually the simpler tool; our guide to the best database for mobile apps compares the options.


How MongoDB Runs a Query

A find or aggregate goes through the same steps on every server, and knowing them explains most of this cheat sheet.

  1. The driver picks a server using the read preference and sends the command over a pooled connection; on a sharded cluster it goes to mongos, which routes it to the shards that own the data.
  2. The server parses the filter into a query shape and checks the plan cache for a plan that won before for the same shape.
  3. Without a cached plan, the planner lists candidate plans from the available indexes, runs them side by side for a short trial, and keeps the one that returns results with the least work.
  4. The executor walks the chosen index (IXSCAN), fetches the documents it points to (FETCH), applies the rest of the filter, and sorts in memory only when no index provides the order.
  5. Results go back in batches of up to 16 MiB; the cursor stays open on the server and getMore fetches the next batch as the client iterates.
  6. A write changes the document in the WiredTiger cache, records the change in the journal and the oplog, and is acknowledged once the members required by the write concern have it.
  7. Secondaries copy the oplog and apply the same changes, which is what drives replication, change streams and point in time recovery.

Most slow queries go wrong at step 3 or 4, when no index matches the filter and sort, so the server reads far more documents than it returns. The explain section shows how to see this, and the index section how to fix it.


MongoDB, PostgreSQL and MySQL Compared

The differences that matter when choosing, or when moving code from one to another.

QuestionMongoDBPostgreSQLMySQL
Data modeldocuments in collectionstables, with jsonb for documentstables, with a JSON type
Schemaflexible, optional $jsonSchema validationfixed, changed with migrationsfixed, changed with migrations
Query languageMQL and the aggregation pipelineSQLSQL
Joins$lookup, usually avoided by embeddingfull SQL joinsfull SQL joins
Scaling outbuilt in shardingextensions such as CitusVitess or application sharding
High availabilityreplica sets with automatic failoverstreaming replication plus a tool such as PatroniGroup Replication or InnoDB Cluster
LicenseSSPL for the server, Apache for driversPostgreSQL LicenseGPL plus commercial

Moving from SQL is mostly a change of habits: model around how the data is read, embed instead of joining where the child data is small and bounded, and let indexes follow the queries. The SQL to MongoDB button in the toolbox converts statements, and the comparison section maps the terms. For MySQL specifics, see the MySQL cheat sheet.


Common MongoDB Mistakes

The same problems show up in most MongoDB deployments that grew without someone watching them.

In Schema and Queries

  • Arrays that grow without limit inside one document, until updates slow down and the 16 MiB limit is near.
  • A relational schema copied as is, with a $lookup on every request.
  • Compound indexes in the wrong order, so the server sorts in memory; follow the equality, sort, range rule.
  • Case insensitive or unanchored regex searches on large collections instead of a collation index or search.
  • Large skip values for pagination, where keyset pagination stays fast on every page.
  • Dates stored as strings and money stored as doubles.

In Operations

  • Servers reachable from the internet without authentication, or with bindIp set to 0.0.0.0 and no firewall.
  • A new MongoClient per request, which exhausts connections under load.
  • Two member replica sets, or arbiters, that cannot keep a majority when one member fails.
  • An oplog window shorter than the longest maintenance, forcing full resyncs.
  • Backups that were never restored.
  • Raising the feature compatibility version the moment the binaries are upgraded, which removes the easy way back.

How to Learn MongoDB Well

Start With Documents and Queries

Run a local server in a container with the Docker cheat sheet, load a sample dataset and practise find, the update operators and the aggregation pipeline in mongosh. Because documents are JSON at heart, the JSON cheat sheet helps with the format itself, and the CSV to JSON converter turns spreadsheets into documents you can import. Then read explain('executionStats') for every query that matters until IXSCAN, FETCH and SORT feel familiar.

Then Learn to Design and Operate It

Schema design is where MongoDB projects succeed or fail, so study the embedding rules and patterns before a large project. After that, run a three member replica set, practise a restore, and learn how the choice of shard key limits software scalability later. On Android, our guide on how to use MongoDB in Android Studio covers the mobile side, and the Python cheat sheet pairs well with PyMongo.


How This MongoDB Cheat Sheet Is Maintained

This page is written and maintained by Bogdan Sandu for TMS Outsource, a software development company. It was checked against the MongoDB 9.0, 8.3 and 8.0 release notes and the current manual on September 29, 2026. If a snippet is wrong or out of date, the date in the byline shows when it was last reviewed.


MongoDB Questions People Actually Ask

The questions developers search for most about MongoDB and about this cheat sheet, answered in a few sentences each.

What is MongoDB used for?

MongoDB stores application data as JSON like documents: product catalogues, user profiles, content, orders, sessions, events and sensor readings. It runs web and mobile back ends, real time analytics with change streams and the aggregation pipeline, IoT platforms with time series collections, and AI features with vector search, either self-managed or as the Atlas cloud service.

Is MongoDB a SQL or NoSQL database?

MongoDB is a NoSQL document database. It does not use SQL tables or the SQL language; queries are written as documents, such as { status: 'paid' }, and more complex work goes through the aggregation pipeline. It still offers what many people associate with SQL databases, including secondary indexes, joins through $lookup, schema validation and multi document ACID transactions.

What is the difference between mongo and mongosh?

mongo was the legacy shell, deprecated in 5.0 and removed from the server packages in 6.0. mongosh is its replacement: a Node.js based shell with syntax highlighting, autocompletion, better error messages and the same helpers such as show dbs and use. Scripts written for mongo mostly run unchanged, apart from number handling, since mongosh stores whole numbers as 32 bit integers instead of doubles.

How do I list databases and collections in MongoDB?

In mongosh, show dbs lists the databases that contain data, use name switches to one, and show collections or db.getCollectionNames() lists its collections. From a driver, call listDatabases on the admin database and listCollections on a database. A database created with use appears in the list only after its first write.

Which MongoDB version should I use?

Use the latest major version your platform and drivers support. As of September 2026 that is MongoDB 9.0 for new projects, with 8.0 as the conservative choice, supported until October 31, 2029. MongoDB 7.0 reaches end of life on August 31, 2027, so plan the move from it, one major version at a time, and raise the feature compatibility version only after the application has run on the new binaries for a while.

How do I join collections in MongoDB?

Use the $lookup stage in an aggregation pipeline: it matches localField in the input documents with foreignField in the other collection and adds the matches as an array. Index the foreign field, and $unwind the result when you expect one match. Often the better answer is to embed the related data, or copy the few fields you display, so no join is needed at read time.

How do I speed up a slow MongoDB query?

Run explain('executionStats') and compare nReturned with totalKeysExamined and totalDocsExamined. A COLLSCAN or a large gap between documents examined and returned means a missing or poorly ordered index; a SORT stage means the index does not match the sort. Build a compound index in equality, sort, range order, project only the fields you need, and use the profiler or $queryStats to find the queries worth fixing first.

How do I back up and restore a MongoDB database?

For small and medium databases, mongodump with --gzip and --archive creates a compressed backup that mongorestore loads back, and --oplog makes a dump of a running replica set consistent. For large deployments use filesystem snapshots of a hidden secondary, Ops Manager or Cloud Manager, Percona Backup for MongoDB, or Atlas cloud backup with point in time restore. Restore a backup regularly to prove it works.

Is this MongoDB cheat sheet up to date?

Yes. It covers MongoDB 7.0, 8.0, 8.3 and 9.0 and was checked against the release notes and the manual on September 29, 2026. Every snippet that needs a newer release names the version that added it, the server picker hides what your version cannot run, rows that need Enterprise or Atlas say so, and the date in the byline changes with every revision.

Can I download this MongoDB cheat sheet as a PDF?

Yes. The page has a print stylesheet, so your browser's print command with Save as PDF produces a clean copy: every output and explanation is included, and the search box, navigation and footer are left out. Run a search first to print only the snippets that are still visible.