Databases
Model, query, index, aggregate, scale and secure data in the MongoDB document database.
A path from the document model and BSON types through CRUD, query operators, indexing and the aggregation pipeline, to transactions, replication, sharding and security. It suits backend developers adopting MongoDB and anyone moving from SQL. Each subject links the official MongoDB documentation.
The subjects follow the roadmap.sh MongoDB roadmap.
MongoDB is a document database: records are JSON-like documents grouped into collections, with no fixed schema enforced unless you ask for one. Start by understanding where that model shines, where a relational database is the better fit, and the vocabulary the rest of the docs assume.
Relational databases normalise data into tables and join at read time; document stores keep related data together and scale out by sharding. The real trade-off is query flexibility and constraints versus schema agility and locality.
A source-available document database server (mongod) that stores BSON documents, supports secondary indexes, aggregation, multi-document ACID transactions, replication and sharding. You talk to it through drivers or mongosh.
Good for evolving or nested data read as a whole (catalogues, user profiles, content, event data) and for workloads that must shard. Heavily relational data with many cross-entity joins and strict constraints usually fits Postgres better.
MongoDB's managed cloud service on AWS, Azure and Google Cloud. It runs replica sets and sharded clusters for you and adds backups, monitoring, Atlas Search and Vector Search; the free M0 tier is enough for learning.
Database → collection → document → field, roughly mirroring database → table → row → column. Also learn _id, replica set, primary/secondary, shard, mongod, mongos and mongosh.
Documents are stored as BSON, a binary format with more types than JSON. Model around how the application reads data: embed what is read together, reference what grows without bound or is shared. Choosing the right numeric and date types up front avoids painful migrations.
BSON is length-prefixed binary, so it is fast to traverse and supports dates, binary, 64-bit integers and decimals. Tools show it as Extended JSON, where {"$date": ...} or {"$oid": ...} keep the type information.
Nest sub-documents and arrays to keep related data in one document and read it in one round trip. Query nested fields with dot notation ("address.city"), and keep arrays bounded: a document cannot exceed 16 MB.
An embedded document used as a field value. Equality matching on a whole sub-document is order-sensitive, so query individual fields with dot notation instead.
An ordered list of any BSON values. A query on an array field matches if any element matches, and indexes on arrays become multikey indexes with one entry per element.
UTF-8 text. Sorting and comparison are binary by default; set a collation when you need case-insensitive or locale-aware ordering.
The default _id type: 12 bytes made of a timestamp, a random value and a counter, generated by the driver. It sorts roughly by creation time and exposes that time via getTimestamp().
true or false. Do not mix with 0/1 or strings in the same field, or queries and indexes will silently miss documents.
A signed 64-bit count of milliseconds since the Unix epoch, always stored in UTC. Store real Date values rather than strings so range queries, TTL indexes and date operators work.
An explicit null value. { field: null } matches both documents where the field is null and where it is missing; use $type or $exists to tell them apart.
The 64-bit IEEE 754 float, and the default number type when you type a literal in mongosh. Fine for measurements, wrong for money because of rounding.
A 32-bit signed integer, created explicitly with NumberInt() or Int32() in the shell. Drivers map native integers to it when they fit.
A 64-bit signed integer, created with NumberLong() or Long in drivers. Use it for counters and IDs that can exceed two billion; JavaScript clients must take care not to lose precision.
A 128-bit decimal floating point with 34 digits of precision, created with NumberDecimal(). The right choice for currency and other values that must round exactly.
BSON also carries types you rarely create yourself: some exist for internal use, some only for comparison edge cases and some are deprecated. Recognise them in old data and in replication internals rather than designing around them.
Raw bytes with a subtype byte, used for UUIDs (subtype 4), hashes, small files and encrypted fields. Anything larger than a few megabytes belongs in GridFS or object storage.
An internal type pairing seconds with an increment, used in the oplog and for cluster time. Use Date for application timestamps, not this.
A regex can be stored as a value as well as used in a query. Most of the time you will only use it in queries, via $regex or a literal /pattern/.
Stores JavaScript code as a value. Server-side JavaScript ($where, $function, map-reduce) is slow and deprecated in places; aggregation operators are the modern replacement.
Deprecated BSON type kept for backward compatibility. Drivers convert JavaScript undefined to null or drop the field; never rely on it.
A deprecated type that behaves like a string in most drivers. You will only meet it in data written by very old tools.
A special value that compares lower than every other BSON value. Shard key ranges use it to describe "from the very beginning".
The counterpart of MinKey: compares higher than everything else, marking the open upper end of chunk ranges in a sharded cluster.
Collections are created implicitly on first insert, or explicitly with db.createCollection() when you need options like validation, capped size or time series. The CRUD methods have single and many variants; learn their filters, options and return values in mongosh and you know them in every driver.
insertOne() and insertMany() add documents and return the generated _ids. insertMany is ordered by default and stops at the first error; pass { ordered: false } to keep going.
find(filter, projection) returns a cursor, findOne() returns the first match. Chain sort(), limit() and skip(), and use findOneAndUpdate() when you need to read and modify atomically.
updateOne(), updateMany() and replaceOne() take a filter and update operators like $set, $inc, $push and $unset. { upsert: true } inserts when nothing matches; pipeline updates allow computed values.
deleteOne() and deleteMany() remove matching documents; an empty filter deletes everything, so double-check it. Dropping the collection is far faster than deleting all documents.
Sends a batch of mixed insert, update, replace and delete operations in one call, ordered or unordered. Use it for imports and sync jobs to cut network round trips.
countDocuments(filter) gives an accurate count by running a query; estimatedDocumentCount() reads collection metadata and is instant but ignores filters. Avoid the deprecated count().
Checks a collection's data and index structures for corruption and reports problems. It takes locks and can be slow, so run it in a maintenance window. Not to be confused with schema validation through $jsonSchema.
Queries return a cursor that fetches results in batches as you iterate. Close cursors you abandon, tune batchSize(), and remember idle cursors time out on the server after ten minutes by default.
Filters are documents built from operators that start with $. Comparison, logical, element, array and evaluation operators combine into precise queries, and the same operators appear inside $match in aggregations. Make sure the fields you filter on are indexed.
Pattern matching on strings with PCRE syntax. Only a case-sensitive prefix pattern like /^abc/ can use an index efficiently; for real text search use a text index or Atlas Search.
The second argument of find() decides which fields come back. Returning only what you need saves bandwidth and can let an index cover the whole query.
Inclusion projection: { name: 1, email: 1 } returns only those fields plus _id. You cannot mix inclusions and exclusions, except for excluding _id.
Exclusion projection: { password: 0 } returns everything except the listed fields. Handy for dropping large or sensitive fields.
Returns part of an array, such as { comments: { $slice: -5 } } for the last five, or [skip, limit] for paging within an array.
Compare a field against a value. Values of different BSON types compare by a fixed type order, so a numeric $gt will not match strings; keep field types consistent.
Equality; { age: 30 } is shorthand for { age: { $eq: 30 } }. Against an array field it matches if any element equals the value.
Not equal; also matches documents missing the field. Negations are selective poorly, so they rarely use indexes well.
Strictly greater than. Combine with $lt on the same field for an open range, e.g. { price: { $gt: 10, $lt: 20 } }.
Greater than or equal. The usual lower bound for date ranges like "everything since midnight".
Strictly less than. Paired with $gte it gives half-open ranges, which avoid double-counting boundary values across buckets.
Less than or equal, the inclusive upper bound. Ranges on an indexed field turn into efficient index bounds.
Matches any value in a list: { status: { $in: ["new", "open"] } }. Cleaner and faster than a chain of $or on the same field.
Matches values not in the list, including documents missing the field. Like other negations it usually scans many index keys.
Combine conditions. Listing several fields in one filter is already an implicit AND; reach for explicit logical operators when you need OR, negation, or two conditions on the same field.
Explicit AND over an array of expressions. Needed when the same field or the same operator appears twice, for example two $or clauses.
Matches if any clause matches. Each clause can use its own index, but only if every clause is indexable; otherwise the query falls back to a collection scan.
Inverts one operator expression on a field, such as { price: { $not: { $gt: 100 } } }. It also matches documents that lack the field.
Matches documents where none of the clauses are true, including documents missing those fields.
Query on the presence or type of a field rather than its value. In a flexible schema these are how you find old-format documents during a migration.
{ field: { $exists: true } } matches documents that have the field, even if its value is null. A sparse or partial index can make these queries cheap.
Matches a field by BSON type, by name ("string", "number") or number. Useful for finding rows written with the wrong type before adding schema validation.
Operators made for array fields. Plain conditions on an array can be satisfied by different elements, so learn when you need every condition to hold on the same element.
Matches arrays that contain every listed value, in any order: { tags: { $all: ["db", "nosql"] } }.
Requires one single element to satisfy all conditions, e.g. an item with qty > 5 and size: "M" at once. Without it, each condition could match a different element.
Matches arrays of an exact length. It takes no ranges and cannot use an index, so store a separate count field if you query lengths often.
Without an index every query scans the whole collection. Create indexes with createIndex() to match your real query shapes, and remember each one costs memory and slows writes, so drop the ones $indexStats shows nobody uses.
An index on one field, ascending or descending (direction does not matter for a single field). Every collection already has a unique one on _id.
One index over several fields. Order them by the ESR rule: equality fields first, then sort fields, then range fields; a prefix of the index can serve queries on its own.
A self-managed text index enables $text search with stemming and stop words, limited to one per collection. On Atlas, Atlas Search is far more capable.
A TTL index on a date field with expireAfterSeconds makes a background task delete old documents, which is ideal for sessions, logs and tokens. Deletion runs about once a minute, so it is not exact.
2dsphere indexes GeoJSON points and shapes on a sphere for $near, $geoWithin and $geoIntersects queries. Store coordinates as longitude first, then latitude.
Lucene-based indexes managed by Atlas and queried with the $search aggregation stage, adding relevance scoring, fuzzy matching, autocomplete and facets. Atlas Vector Search uses the same mechanism for embeddings.
Most MongoDB performance problems are a missing index, a bad schema shape or a working set that no longer fits in RAM. Measure with explain(), the profiler and the slow query log before changing anything.
Run explain("executionStats") and compare totalDocsExamined with nReturned; a COLLSCAN or a large gap means a missing or wrong index. Covered queries answer entirely from the index.
Design indexes for your most frequent queries and sorts, keep them in memory, and prefer one good compound index over many single-field ones. Partial indexes keep size down when only a subset is queried.
Size the WiredTiger cache, use XFS on Linux, disable transparent huge pages where advised, and set connection pool sizes in drivers. Change one setting at a time and measure.
The aggregation framework processes documents through a pipeline of stages, each transforming the stream, for reporting, reshaping and joins. Put $match and $sort early so they can use indexes, and mind the 100 MB per-stage memory limit (allowDiskUse).
A pipeline is an array of stages run with db.collection.aggregate(). Stages ($match, $group) shape the stream; expression operators ($sum, $concat, $cond) compute values inside stages.
Filters documents with normal query syntax. As the first stage it can use indexes, so filter as early as you can.
Groups documents by an _id expression and computes accumulators such as $sum, $avg, $max, $push and $first for each group.
Orders documents; it can use an index only near the start of a pipeline. Followed by $limit, the server keeps just the top N in memory.
Reshapes each document: include, exclude, rename or compute fields. $addFields/$set is simpler when you only add a field and keep the rest.
Discards the first N documents. Large skips still walk past every skipped document, so page deep result sets with a range on a sorted key instead.
Passes on only the first N documents. Place it right after $sort for efficient top-N queries.
Turns one document with an array into one document per element, ready for grouping. preserveNullAndEmptyArrays keeps documents with no elements.
A left outer join to another collection in the same database, by matching fields or with a sub-pipeline. Index the foreign field, and if you join constantly, reconsider embedding.
An accumulator in $group ({ total: { $sum: "$amount" } }, or { $sum: 1 } to count) and an expression that adds array elements elsewhere. Non-numeric values are ignored.
Single-document writes are always atomic, which is why good document design rarely needs more. Multi-document ACID transactions work on replica sets and sharded clusters; use the driver's withTransaction() callback so transient errors are retried, and keep transactions short.
Write concern sets how many members must acknowledge a write (w: "majority" is the default and survives failover). Read concern sets what data a read may see, from local to majority and snapshot.
Modern drivers retry a read or a single write once after a network error or primary election, without duplicating the write. Both are on by default; multi-document writes like updateMany are not retried.
Around the server sit the drivers your code uses, mongosh and Compass for exploring data, connectors that stream data to other systems, and the database tools for dumps and restores.
Official drivers exist for Node.js, Python, Java, Go, C#, Rust and more. Create one client per process and reuse it: it manages the connection pool, server discovery and retries.
The Kafka Connector works as a source, publishing change stream events to topics, and as a sink, writing topic records into collections. Common for event-driven and CDC pipelines.
The Spark Connector reads collections into DataFrames and writes results back, pushing filters down to MongoDB where it can. Used for large-scale analytics and ML jobs.
Elastic's MongoDB connector syncs collections into an Elasticsearch index for full-text search. On Atlas, consider Atlas Search first to avoid running and syncing a second system.
Exports data to BSON files, per database or collection, with --oplog for a consistent point in time on a replica set. Good for small deployments and migrations; large clusters need filesystem snapshots or Atlas backups.
Loads a mongodump output back into a deployment, rebuilding indexes afterwards. --nsFrom/--nsTo rename namespaces, --drop replaces existing collections, and --oplogReplay applies the captured oplog.
Replication gives you redundancy and automatic failover; sharding spreads data and writes across machines. Scale vertically and fix queries first, because sharding adds real operational complexity and a shard key is hard to change.
A primary takes writes and secondaries replicate its oplog; if the primary fails, the members elect a new one within seconds. Run at least three members, and use read preferences to send some reads to secondaries.
Data is partitioned by a shard key across shards (each a replica set), with mongos routers and config servers in front. Choose a key with high cardinality and even writes, and make most queries include it.
A self-hosted mongod should never be reachable from the internet without access control; exposed open databases have been wiped by ransom bots for years. Enable authentication, grant least privilege, encrypt traffic and keep an audit trail.
Turn on security.authorization, create users, and grant built-in roles like read and readWrite per database, or custom roles with specific privileges. Applications should never connect as root.
Clients and cluster members authenticate with TLS certificates instead of passwords. A good fit for internal cluster authentication and for services that already have a PKI.
Enterprise Advanced feature that lets users authenticate with existing Kerberos tickets, usually from Active Directory, for single sign-on in corporate networks.
Enterprise feature where mongod forwards username and password checks to an LDAP directory, and can map LDAP groups to MongoDB roles.
Records authentication, schema changes, user management and optionally CRUD events to a file or syslog, with filters to limit volume. Available in Enterprise and on Atlas dedicated clusters.
Encrypt data in transit with TLS, at rest on disk, and, for the most sensitive fields, in use on the client so the server never sees plaintext. Each layer protects against a different attacker.
Configure net.tls.mode: requireTLS with a certificate so every client and cluster connection is encrypted. Atlas enforces TLS on all connections.
The WiredTiger encrypted storage engine encrypts data files with keys from a KMIP server (Enterprise); Atlas encrypts storage by default and lets you bring your own cloud key.
CSFLE lets the driver encrypt chosen fields before they leave the application, with keys in a KMS. Deterministic encryption supports equality queries; random encryption does not support queries.
The newer client-side scheme that keeps fields randomly encrypted yet still supports equality and range queries on them. Check which query types your server version supports before designing around it.