Skip to main content
Quick Reference

MongoDB Cheatsheet

MongoDB on one page — mongosh inserts, finds, updates, deletes, indexes, the aggregation pipeline, $lookup, and the document rules interviews ask about.

10 sections 10 tables 14 code snippets

Connect & switch

Open mongosh

mongosh "mongodb://localhost:27017"

Pick a database

use shop
db.books.insertOne({ title: "Dune", pages: 412 })
db.books.find({ title: "Dune" })

The three names

NameMeaning
mongoshThe current shell. The old mongo shell is retired
Databaseuse shop selects it. The database appears after the first write
Collectiondb.books is a collection. It is created by the first insert
DocumentOne JSON-like record. _id is added when you omit it
Port 27017The local default. Atlas uses a mongodb+srv:// URL
show dbsLists databases that contain data. An unused use does not show up

This page is mongosh and the server. Mongoose is a separate Node library with its own models.

Insert

One, then many

db.books.insertOne({
  title: "Dune",
  pages: 412,
  tags: ["sf", "classic"],
  author: { name: "Frank Herbert" }
})

db.books.insertMany([
  { title: "Neuromancer", pages: 271 },
  { title: "Foundation", pages: 255 }
])

What comes back

CallResult
insertOneinsertedId is the new _id
insertManyinsertedIds maps each index to an _id
Ordered, the defaultThe first error stops the batch. Later documents are not tried
{ ordered: false }The batch keeps going after an error
Duplicate _idThe write fails. _id is unique inside the collection
Extra fieldsAllowed. Two documents in one collection need not share a shape

Find

Filter, project, page

db.books.find(
  { pages: { $gte: 300 }, tags: "sf" },
  { title: 1, pages: 1, _id: 0 }
).sort({ pages: -1 }).limit(10)

One element of an array

db.books.find({
  reviews: {
    $elemMatch: { stars: { $gte: 4 }, by: "Ada" }
  }
})

Read rules

FormMatches
{}Every document. find returns a cursor, not an array
{ tags: "sf" }An array that contains that value
{ "author.name": "Frank Herbert" }A field inside an embedded document
$gte, $in, $neCompare, membership, and not-equal. $ne also matches a missing field
$elemMatchSeveral conditions on the same array element
{ title: 1, _id: 0 }Inclusion. Mixing include and exclude is an error, except for _id

Update

Change two fields

db.books.updateOne(
  { title: "Dune" },
  { $set: { pages: 416 }, $inc: { editions: 1 } }
)

Insert when missing

db.books.updateOne(
  { title: "Dune" },
  {
    $set: { pages: 416 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)

Operators

OperatorEffect
$setSets fields. Creates them when they are missing. Other fields stay
$unsetRemoves fields
$incAdds a number. A missing field starts at that number
$push / $addToSetAppends to an array. $addToSet skips a value that is already there
$pullRemoves matching array values
replaceOneSwaps the whole document except _id. Omitted fields are gone

matchedCount: 1 and modifiedCount: 0 means the document was already in that state. updateOne changes the first match. Pass sort when several documents match and the choice matters. $setOnInsert runs only when the upsert inserts.

Delete

One row, or the short ones

db.books.deleteOne({ title: "Dune" })
db.books.deleteMany({ pages: { $lt: 100 } })

Three different removals

CallRemoves
deleteOneThe first match. deletedCount is 0 or 1
deleteManyEvery match. {} matches the whole collection
drop()The collection, its documents, and its indexes
deleteMany({})The documents only. Indexes remain
A databasedb.dropDatabase(). There is no undo

Indexes

A compound index

db.books.createIndex({ title: 1, pages: -1 })
db.books.createIndex(
  { title: 1 },
  { unique: true }
)
db.books.find({ title: "Dune" }).explain("executionStats")

What the planner uses

IndexServes
{ title: 1 }Equality, range, and sort on title. 1 is ascending, -1 is descending
{ title: 1, pages: -1 }Queries on title, and on title plus pages. Not on pages alone
Equality, then sort, then rangeThe field order that lets one compound index do all three
unique: trueRejects a second document with the same key. A missing field counts as null, so only one document may omit it
IXSCAN vs COLLSCANexplain shows an index scan or a full collection walk
TTLexpireAfterSeconds on a date field. A background task deletes expired documents about once a minute

Aggregation

Match, group, sort

db.orders.aggregate([
  { $match: { status: "paid" } },
  { $group: {
      _id: "$customerId",
      total: { $sum: "$amount" },
      orders: { $sum: 1 }
  }},
  { $sort: { total: -1 } },
  { $limit: 10 }
])

Stages you will write

StageJob
$matchThe same filters as find. Put it first so an index can apply
$groupOne document per key. _id: "$customerId" is the key. _id: null is a single bucket
$sumAn accumulator. $sum: 1 counts. $avg, $min, and $max are the others you meet first
$project / $addFieldsShape the document. $addFields keeps the fields you did not mention
$sort then $limitTop-N. An unindexed sort of a huge set can run out of memory
$out / $mergeWrite the pipeline to a collection. $out replaces that collection

$lookup

A left join

db.orders.aggregate([
  { $lookup: {
      from: "books",
      localField: "bookId",
      foreignField: "_id",
      as: "book"
  }},
  { $unwind: {
      path: "$book",
      preserveNullAndEmptyArrays: true
  }}
])

Join rules

FactWhy it matters
Left outer joinAn order with no book is still in the result, and book is []
as is always an arrayOne match is still an array of one
$unwindTurns the array into one document per element. The default drops an empty array
preserveNullAndEmptyArraysKeeps the parent when nothing matched
Types must agreeA string bookId does not match an ObjectId _id
Pipeline formUse it when the join is not a single-field equality

Document shape

Embed the data you read together

db.books.insertOne({
  title: "Dune",
  author: { name: "Frank Herbert" },
  tags: ["sf", "classic"]
})

db.books.find({ "author.name": "Frank Herbert", tags: "sf" })

Embed or reference

ShapeWhen
EmbedThe child is small and you always read it with the parent. One book and its author name
ReferenceThe child is large, shared, or grows without a bound. An order points at a book _id
_idUnique in the collection. The default is an ObjectId, which also carries a timestamp
One document is atomicA write to one document is atomic. A multi-document transaction needs a replica set
16 MBThe maximum BSON document size. An unbounded embedded array will hit it
countDocumentsAn exact count. estimatedDocumentCount is the fast metadata estimate. count() is deprecated

Interview traps

Traps worth memorising

TrapWhat happensPrefer
updateOne(filter, { pages: 416 })Rejected. That object is not an update operator$set, or replaceOne when you mean a new document
{ _id: "6740..." }A string is not an ObjectId, so nothing matchesObjectId("6740...")
{ title: 1, pages: 0 }Inclusion and exclusion in one projection is an errorInclude the fields you want and set _id: 0
{ pages: null }Matches null and missing$exists: false for missing. { $type: "null" } for a stored null
Two conditions on an arrayEach condition may hit a different element$elemMatch
find() treated as an arrayIt is a cursor. The shell prints a page of 20.toArray() when you need the whole list
deleteMany({})Deletes every document in the collectionA filter, or drop() when you also want the indexes gone
Query on the second index field onlyThe compound index is not usedThe equality field first, matching the index prefix
$unwind after $lookupParents with no match disappearpreserveNullAndEmptyArrays: true
Unique index plus two upsertsBoth can insert if the key is not unique yetA unique index on the filter fields
$out pointed at a live collectionThat collection is replaced$merge when you mean to add or update
Case{ title: "dune" } does not match "Dune"An exact value, or a collation when case should not matter

The update document

db.books.updateOne(
  { title: "Dune" },
  { $set: { pages: 416 } }
)

The id type

db.books.findOne({
  _id: ObjectId("6740aabbccddeeff00112233")
})

How to use this page: open mongosh, use shop, and insertOne a book. Then find it with a projection that drops _id, and updateOne the page count with $set.