Get started
Introduction
MongoDB stores JSON-like documents in collections. This reference covers mongosh queries, updates, pipelines, indexes, and validation.
- MongoDB manual (mongodb.com)
- mongosh reference (mongodb.com)
- Aggregation pipeline (mongodb.com)
Start a local server
docker run --name mongo -d -p 27017:27017 \
-v mongo-data:/data/db \
mongodb/mongodb-community-server:9.0-ubi9-slim
The named volume keeps data after the container is removed.
Connect with mongosh
mongosh
mongosh "mongodb://localhost:27017/app"
use app
show collections
A URI selects the database at connect time; use switches it in a shell.
See: mongosh
Insert documents
db.users.insertOne({ name: 'Ada', age: 36 })
db.users.insertMany([
{ name: 'Bob', age: 29 },
{ name: 'Cy', age: 41 }
])
MongoDB adds _id when omitted; insertMany returns one ID per document.
See: insertOne, insertMany
Find documents
db.users.find()
db.users.findOne({ name: 'Ada' })
db.users.find({ age: { $gte: 30 } })
find() returns a cursor; findOne() returns the first match.
See: find
Filter documents
Predicate reference
| Predicate | Meaning |
|---|---|
$ne | Not equal to a value |
$gt | Greater than a value |
$gte | Greater than or equal |
$lt | Less than a value |
$lte | Less than or equal |
$in | Matches any listed value |
$nin | Matches no listed value |
$and | All conditions match |
$or | Any condition matches |
$nor | No condition matches |
$not | Inverts an expression |
$exists | Field is present or absent |
$type | Field has a BSON type |
$all | Array holds every listed value |
$elemMatch | One element meets all tests |
$size | Array has an exact length |
$regex | Value matches a regex |
$expr | Compares fields with expressions |
find() filters take these predicates; bare field: value means equality.
See: query operators
Compare values
db.users.find({ status: 'active' })
db.users.find({
age: { $gte: 18, $lt: 65 }
})
db.users.find({
role: { $in: ['admin'] }
})
Bare field: value means equality; operators can share one field.
See: query operators
Combine conditions
db.users.find({
status: 'active',
age: { $gte: 18 }
})
db.users.find({
$or: [{ status: 'vip' }, { age: 18 }]
})
Listed fields combine with AND; $or takes an array of conditions.
See: $or
Match arrays
db.posts.find({ tags: 'mongodb' })
db.posts.find({
tags: { $all: ['mongodb', 'db'] }
})
db.posts.find({
comments: {
$elemMatch: { score: { $gt: 5 } }
}
})
A plain value matches any element; $elemMatch groups tests on one element.
See: $elemMatch
Check fields
db.users.find({
email: { $exists: true }
})
db.users.find({ age: { $type: 'int' } })
Presence and BSON type checks filter on the field itself.
See: $exists
Search text
db.articles.createIndex({ title: 'text' })
db.articles.find({
$text: { $search: '"exact phrase"' }
})
db.articles.find({
$text: { $search: 'mongodb -sql' }
})
A text index is required, and a collection allows only one.
See: $text
Shape results
Project fields
db.users.find(
{ age: { $gte: 18 } },
{ name: 1, email: 1, _id: 0 }
)
Inclusion keeps named fields; _id stays unless excluded.
See: projection
Sort and limit
db.users.find()
.sort({ age: -1 })
.limit(10)
db.users.find()
.sort({ age: 1 })
.skip(20)
.limit(10)
Pair skip with a sort for stable pages of results.
See: cursor.sort
Count and distinct
db.users.countDocuments({
status: 'active'
})
db.users.distinct('address.city')
distinct returns unique values of a field across matches.
See: countDocuments
Change documents
Update fields
db.users.updateOne(
{ email: 'ada@example.com' },
{ $set: { age: 37, 'address.city': 'Rome' } }
)
db.users.updateMany(
{ status: 'inactive' },
{ $set: { status: 'archived' } }
)
Dot notation reaches nested fields; updateMany updates every match.
See: updateOne
Increment and multiply values
db.products.updateOne(
{ sku: 'A1' },
{ $inc: { stock: -1 }, $mul: { price: 1.1 } }
)
$inc is atomic; $mul scales a numeric field.
See: $inc
Update arrays
db.users.updateOne({ name: 'Ada' },
{ $push: { tags: 'ops' } })
db.users.updateOne({ name: 'Ada' },
{ $addToSet: { tags: 'admin' } })
db.users.updateOne({ name: 'Ada' },
{ $pull: { tags: 'ops' } })
$addToSet skips duplicates; $pull removes every matching element.
See: $push
Upsert a document
db.users.updateOne(
{ email: 'cy@example.com' },
{ $set: { name: 'Cy' },
$setOnInsert: { createdAt: new Date() } },
{ upsert: true }
)
Upsert inserts when nothing matches; $setOnInsert runs only then.
See: updateOne
Delete documents
db.users.deleteOne({ email: 'ada@example.com' })
db.users.deleteMany({ status: 'archived' })
db.users.deleteMany({})
An empty filter deletes every document; deletes cannot be undone.
See: deleteMany
Aggregate
Build a pipeline
db.orders.aggregate([
{ $match: { status: 'complete' } },
{ $group: {
_id: '$customerId',
total: { $sum: '$amount' }
} },
{ $sort: { total: -1 } },
{ $limit: 10 }
])
Stages run in order; filter early to reduce documents for later stages.
See: aggregation pipeline
Accumulate values
db.sales.aggregate([{ $group: {
_id: '$category',
count: { $sum: 1 },
average: { $avg: '$amount' },
items: { $push: '$item' }
} }])
$sum: 1 counts documents; accumulators collect values within $group.
See: $group
Reshape documents
db.users.aggregate([{ $project: {
name: 1,
label: {
$cond: [{ $gte: ['$score', 5] }, 'high', 'low']
},
tagCount: { $size: '$tags' }
} }])
$project keeps named fields and adds computed ones.
See: $project
Join collections
db.posts.aggregate([
{ $lookup: {
from: 'authors', localField: 'authorId',
foreignField: '_id', as: 'author'
} },
{ $unwind: '$author' }
])
$lookup adds an array of matches; $unwind emits a document for each.
See: $lookup
Use expression variables
db.orders.aggregate([{ $project: {
customer: '$$ROOT.customerId',
doubled: { $multiply: ['$amount', 2] }
} }])
$$ROOT is the whole document; $name reads a field from it.
Indexes and performance
Create indexes
Single field
db.users.createIndex({ email: 1 })
Unique constraint
db.accounts.createIndex({ email: 1 }, { unique: true })
Compound
db.orders.createIndex({ customerId: 1, createdAt: -1 })
Text
db.pages.createIndex({ title: 'text', body: 'text' })
1 sorts ascending, -1 descending; compound index order matters.
See: createIndex
Inspect indexes
db.users.getIndexes()
db.users.totalIndexSize()
Every collection has an _id index; extra indexes slow down writes.
See: getIndexes
Explain a query
db.users.find({ email: 'ada@example.com' })
.limit(1)
.explain('executionStats')
.queryPlanner.winningPlan
Output
{
isCached: false,
stage: 'EXPRESS_IXSCAN',
keyPattern: { email: 1 },
indexName: 'email_1'
}
indexName names the chosen index; COLLSCAN means no index was used.
See: Explain slow queries
Force an index
db.users.find({ email: 'ada@example.com' })
.hint({ email: 1 })
Use hint() to test an index, not as a permanent fix.
See: cursor.hint
Expire documents
db.sessions.createIndex(
{ createdAt: 1 }, { expireAfterSeconds: 3600 }
)
TTL deletion runs in the background, so removal is not immediate.
See: TTL indexes
Schema and design
Validate documents
db.createCollection('users', {
validator: { $jsonSchema: {
bsonType: 'object',
required: ['email'],
properties: {
email: { bsonType: 'string' }
}
} }
})
New and updated documents must pass the validator.
See: schema validation
Change validation
db.runCommand({
collMod: 'users',
validator: { $jsonSchema: {
bsonType: 'object',
required: ['email', 'name']
} }
})
collMod replaces the rules on an existing collection.
See: collMod
Embed or reference
| Pattern | Use when |
|---|---|
| Embed | Child reads with the parent and stays small |
| Reference | Child is large or shared across parents |
| Bucket | Events arrive over time without a bound |
Avoid arrays that grow without limit; bucket time-series data instead.
See: data modeling
0 Comments for this cheatsheet. Write yours!