Documents and Queries
A document database stores each record as a self-contained document: a tree of fields, arrays and nested documents, instead of a row of flat columns. MongoDB is the most used one. This page covers what a document is, how documents are read and changed, which operations are atomic, and the aggregation pipeline, which is where joins and grouping happen. The next pages use this to design schemas.
Every example in this series uses the restaurant domain from data modeling, so each design can be compared with its relational version. The examples were run on MongoDB 8.0 with mongosh, and the output shown is its output.
Documents and collections
A restaurant with its address and tables, as one document:
db.restaurants.insertOne({
name: "Trattoria",
city: "Bologna",
address: { street: "Via Zamboni 1", zip: "40126" },
cuisines: ["italian", "emilian"],
tables: [ { number: 1, seats: 4 }, { number: 2, seats: 4 }, { number: 3, seats: 6 } ]
})
{ acknowledged: true, insertedId: ObjectId('6b09ad3b80307195b1ba9f49') }
| Relational | MongoDB |
|---|---|
| database | database |
| table | collection |
| row | document |
| column | field |
| primary key | _id |
| foreign key | a field holding another document's _id, with no constraint |
| join | $lookup in an aggregation, or a second query |
Differences that matter for design:
- Nested values.
addressis a sub-document,cuisinesan array of strings,tablesan array of sub-documents. In the relational schema, the tables were a separate table with a foreign key (relationships); here they live inside the restaurant. - No fixed schema. Two documents in one collection can have different fields. The database does not check types or required fields unless a validator is added (indexes, validation and transactions).
- No referential integrity. A field can hold the
_idof a document that does not exist, and nothing stops it.
Documents are stored as BSON, a binary form of JSON with more types: dates, 64-bit integers, decimals, binary data and ObjectId. A document can be at most 16 MB:
BSONObj size: 18874406 (0x1200026) is invalid. Size must be between 0 and 16793600(16MB)
The limit matters for design: an array that grows without bound (every booking a restaurant ever had) will eventually hit it.
_id and ObjectId
Every document has an _id, unique in its collection and indexed. If the application does not set one, the driver generates an ObjectId: 12 bytes made of a timestamp, a random value and a counter. Ids can be generated by any client without coordination, and they sort roughly by creation time:
const id = new ObjectId()
id.getTimestamp()
ISODate('2026-11-27T16:18:03.000Z')
_id can also be a natural key when one exists and never changes: { _id: "ada@example.com", name: "Ada" }. The trade-offs are those of natural and surrogate keys, and _id cannot be changed after insert.
Reading
find(filter, projection) returns the documents that match a filter, with the fields the projection selects:
db.restaurants.find({ city: "Bologna" }, { _id: 0, name: 1, "address.zip": 1 })
[ { name: 'Trattoria', address: { zip: '40126' } }, { name: 'Osteria' } ]
- Dot notation reaches into sub-documents:
"address.zip". - A filter on an array field matches if any element matches:
{ cuisines: "italian" }finds Trattoria and Osteria. - Operators start with
$:$gt,$in,$exists,$regex, and$and/$orto combine.
Several conditions on an array of documents
Which restaurants have a table number 1 with 8 seats?
db.restaurants.find({ "tables.number": 1, "tables.seats": 8 }, { _id: 0, name: 1 })
[ { name: 'Trattoria' }, { name: 'Osteria' } ]
Neither has such a table. Trattoria matched because table 1 satisfies the first condition and table 3 (8 seats) the second. With dot notation, each condition is checked against any element, not the same one. To require one element that satisfies all conditions, use $elemMatch:
db.restaurants.find({ tables: { $elemMatch: { number: 1, seats: 8 } } }, { _id: 0, name: 1 })
[]
This is the document-database version of the inflated join totals in 16b: a query that looks right and is wrong only on some data.
Writing
insertOne/insertMany, updateOne/updateMany, replaceOne, deleteOne/deleteMany. An update takes a filter and update operators, which change parts of the document without rewriting it:
db.restaurants.updateOne(
{ name: "Sushi Bar" },
{ $set: { city: "Torino" }, $push: { tables: { number: 2, seats: 4 } }, $inc: { version: 1 } }
)
{ name: 'Sushi Bar', city: 'Torino', cuisines: [ 'japanese' ],
tables: [ { number: 1, seats: 2 }, { number: 2, seats: 4 } ], version: 1 }
| Operator | Does |
|---|---|
$set, $unset |
set or remove a field |
$inc |
add to a number |
$push, $pull, $addToSet |
add to an array, remove matching elements, add only if absent |
$ (positional) |
the array element matched by the filter |
The positional operator changes one element of an array in place. Table 3 of Trattoria gets 8 seats:
db.restaurants.updateOne({ name: "Trattoria", "tables.number": 3 }, { $set: { "tables.$.seats": 8 } })
{ tables: [ { number: 1, seats: 4 }, { number: 2, seats: 4 }, { number: 3, seats: 8 } ] }
Atomicity is per document
A write to one document is atomic: all its changes are applied together, and no reader sees half of them. This includes changes to nested documents and arrays. That is the main reason to put data that changes together in one document.
The filter and the update of one updateOne are also one atomic step, which gives a check-then-act without a race (concurrency for LLD). One free table left at 20:00, and two booking requests:
db.slots.insertOne({ _id: "trattoria-2026-12-05T20", free_tables: 1 })
db.slots.updateOne({ _id: "trattoria-2026-12-05T20", free_tables: { $gt: 0 } }, { $inc: { free_tables: -1 } })
db.slots.updateOne({ _id: "trattoria-2026-12-05T20", free_tables: { $gt: 0 } }, { $inc: { free_tables: -1 } })
{ first: 1, second: 0, now: 0 }
The second update matched nothing, because the condition is evaluated and the decrement applied as one step. The application reads modifiedCount and tells the second customer the slot is full. This is the document version of optimistic locking (18g).
Writes that span several documents are not atomic together unless they run in a multi-document transaction (indexes, validation and transactions).
The aggregation pipeline
aggregate runs a list of stages; each stage takes the documents from the previous one and outputs new documents. It covers what SQL does with WHERE, GROUP BY, ORDER BY and joins.
Bookings refer to their restaurant and customer by id:
db.bookings.insertMany([
{ restaurant_id: tr, customer_id: "ada@example.com", starts_at: ISODate("2026-12-05T20:00Z"), party_size: 10, tables: [1, 2] },
{ restaurant_id: tr, customer_id: "bob@example.com", starts_at: ISODate("2026-12-05T20:00Z"), party_size: 2, tables: [3] },
{ restaurant_id: tr, customer_id: "ada@example.com", starts_at: ISODate("2026-12-12T20:00Z"), party_size: 4, tables: [1] }
])
Guests per customer at one restaurant:
db.bookings.aggregate([
{ $match: { restaurant_id: tr } },
{ $group: { _id: "$customer_id", bookings: { $sum: 1 }, guests: { $sum: "$party_size" } } },
{ $sort: { guests: -1 } }
])
[ { _id: 'ada@example.com', bookings: 2, guests: 14 },
{ _id: 'bob@example.com', bookings: 1, guests: 2 } ]
The SQL equivalent is SELECT customer_id, count(*), sum(party_size) FROM bookings WHERE restaurant_id = ? GROUP BY customer_id ORDER BY 3 DESC. $match early in the pipeline can use indexes and reduces what later stages process, the same reason a filter is applied before a join in SQL.
Common stages:
| Stage | SQL counterpart |
|---|---|
$match |
WHERE (before grouping), HAVING (after) |
$project, $addFields |
the SELECT list |
$group |
GROUP BY with aggregates |
$sort, $limit, $skip |
ORDER BY, LIMIT, OFFSET |
$unwind |
one output document per array element |
$lookup |
a left outer join |
$out, $merge |
CREATE TABLE AS, INSERT ... ON CONFLICT |
$unwind turns an array into rows. Seats per restaurant, summing over the embedded tables:
db.restaurants.aggregate([
{ $unwind: "$tables" },
{ $group: { _id: "$name", seats: { $sum: "$tables.seats" }, n: { $sum: 1 } } },
{ $sort: { _id: 1 } }
])
[ { _id: 'Osteria', seats: 10, n: 2 },
{ _id: 'Sushi Bar', seats: 6, n: 2 },
{ _id: 'Trattoria', seats: 16, n: 3 } ]
$lookup: joins
$lookup adds to each document an array with the matching documents of another collection, which $unwind can then flatten:
db.bookings.aggregate([
{ $match: { customer_id: "ada@example.com" } },
{ $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer" } },
{ $unwind: "$customer" },
{ $project: { _id: 0, starts_at: 1, party_size: 1, name: "$customer.name" } }
])
[ { starts_at: ISODate('2026-12-05T20:00:00.000Z'), party_size: 10, name: 'Ada' },
{ starts_at: ISODate('2026-12-12T20:00:00.000Z'), party_size: 4, name: 'Ada' } ]
Joins exist, but they are not where document databases are strong: each $lookup is a lookup per input document into the other collection, which needs an index on foreignField to be fast. A schema that needs $lookup on its most frequent query is usually a sign that the data read together should be stored together (embedding vs referencing).
And nothing checks the references:
db.bookings.insertOne({ restaurant_id: tr, customer_id: "nobody@example.com", party_size: 2 }).acknowledged
true
The booking points to a customer that does not exist. Keeping references valid is the application's job.
Relational and document thinking
The two models start from different questions:
- A relational schema is designed from the data: one table per entity, normalized so every fact is stored once (normalization). Any query can be answered later with joins.
- A document schema is designed from the queries: data read together is stored together, even if that means repeating it. A query that the schema was not designed for may be slow or need a pipeline of
$lookups.
MongoDB has no normalization theory and no algorithm for its schemas, only guidelines. The design aims at three things at once: store the data correctly, answer the frequent queries fast, and do it with a reasonable amount of hardware. The following pages turn these guidelines into a method.