To read Sunset Coffee's order #1 in full in SQL, you join four tables with JOIN: customers, orders, order_items and products. Some databases keep that order in one bundle, so a single read gets all of it.
MongoDB is one of them. It is a document database, the type you met in the Types of Database lesson. MongoDB stores data as documents, shaped much like JSON objects. On disk, documents are saved in a binary form called BSON (Binary JSON). Documents of the same kind are grouped in one collection. Picture Sunset Coffee's filing cabinet. Every order has one folder that holds all its papers: who bought it, what was bought, and the total. All the folders are kept in one drawer. One folder is one document, and the drawer is a collection. Want order #1? Take out one folder, done.
SQL terms in MongoDB's words
The ideas are close to what you know from SQL, only the names differ:
| SQL | MongoDB |
|---|---|
| table | collection |
| row | document |
| column | field |
JOIN |
$lookup |
| index | index (the same) |
| primary key | _id |
Every document must have an _id that is unique in its collection. Indexes work as in SQL too. With db.orders.createIndex({ 'items.product': 1 }) (1 means ascending order), a search by product no longer checks every document.
One order, one document
The orders collection below holds the same three Sunset Coffee orders as the rest of this track. This is how mongosh (MongoDB's command-line program) prints order #1. Its prompt, cafe>, is the name of the database in use. findOne({ _id: 1 }) fetches one document whose _id is 1:
cafe> db.orders.findOne({ _id: 1 })
{
_id: 1,
customer: { _id: 1, name: 'Budi' },
items: [
{ product: 'Milk Coffee', price: 450, qty: 2 },
{ product: 'Toast', price: 500, qty: 1 }
],
total: 1400
}
customeris an embedded document: an object inside the document.itemsis an array of documents. In SQL this needs anorder_itemstable and aJOIN. Here, one read gets everything.- Order #3 (Siti's) has an extra field,
note: 'less sweet', and the other two orders don't have it. NoALTER TABLEneeded: every document may have a different structure. That's what schema-flexible means. - Flexible doesn't mean no rules. Your app has to cope with a missing field. If you want MongoDB to refuse data of the wrong shape, add validation rules with
$jsonSchema.
Searching with find()
find() takes a filter: an object naming a field and its condition. The condition is written with an operator, a word that starts with $. These are the three most common operators, with their results in the // lines:
cafe> db.orders.find({ 'items.product': { $eq: 'Milk Tea' } })
// only order #3
cafe> db.orders.find({ total: { $gt: 750 } })
// orders #1 (1400) and #3 (825)
cafe> db.orders.find({ 'items.product': { $in: ['Milk Tea', 'Toast'] } })
// orders #1 (has Toast) and #3 (has Milk Tea)
$eqmeans equal to.{ 'customer.name': 'Budi' }is short for{ 'customer.name': { $eq: 'Budi' } }, and it finds orders #1 and #2.$gtmeans greater than. There are also$gte(greater than or equal to),$lt(less than) and$lte(less than or equal to).$inmatches when the value is one of a list.- Dot notation (
'items.product', meaning the fieldproductinsideitems) reaches into embedded documents and arrays, and must be written in quotes. When the field is an array, the filter matches as soon as any one element (one item of the array) meets the condition. - When nothing matches, mongosh prints nothing. This page's Lab runs filters like the ones above against the three documents and prints the result in mongosh's format.
Embed or reference
There are two ways to store related data:
- Embed: the data is copied into its parent document (the document that holds it), like
itemsandcustomerabove. - Reference: only its
_idis kept, like a foreign key. The order keepscustomer_id: 1, and Budi's data lives in acustomerscollection.
Say Budi changes his name to Budi Santoso. His name is embedded in orders #1 and #2. A developer then runs db.orders.updateOne({ 'customer._id': 1 }, { $set: { 'customer.name': 'Budi Santoso' } }). The first argument is the filter, and the second is the change: $set puts the new name in the field customer.name. How many orders now carry the new name? updateOne stops at the first matching document, so only 1. Budi now has two names, with no error. The right call is updateMany, which changes every matching document. mongosh answers: two documents match (matchedCount: 2) and both were changed (modifiedCount: 2):
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}
With a reference, db.customers.updateOne({ _id: 1 }, { $set: { name: 'Budi Santoso' } }) is enough. Only 1 document changes, and every order follows, because the orders only keep customer_id. The downside: to read an order with its buyer's name, you need $lookup, MongoDB's JOIN:
db.orders.aggregate([
{ $lookup: { from: 'customers', localField: 'customer_id', foreignField: '_id', as: 'customer' } },
{ $match: { 'customer.name': 'Budi' } }
])
Inside aggregate, $lookup fetches the buyer from customers whose _id equals the order's customer_id and puts it in the field customer. Then $match filters the result like the filter in find().
The rule: embed when data is usually read together and rarely changes on its own. For example, an order's items are always read with the order, and the price paid must not change later anyway. Reference when data stands on its own, is used by many documents, or can grow without limit. Examples are a customer with dozens of orders, or comments on a viral post. One document can be at most 16 MB, so an array that keeps growing has to become a reference.
When MongoDB fits
- Data whose shape varies: a catalogue (coffee has a cup size, bread a jam flavour), a CMS, profiles.
- Data almost always read whole, one document at a time, like an order page.
- Logs and events written nonstop.
MongoDB fits less when the data is related in complicated ways and is often counted across many documents at once, such as "total sales per product per month". That's SQL's strength, covered in the next lesson, SQL vs NoSQL.
⚠️ Data that doesn't follow, misspelt fields
updateOnefor data copied into many documents. The rest keep the old data. UseupdateMany, or make it a reference.- Embedding an array that grows without limit. Comments, logs, history: one day the document hits the 16 MB limit.
- A typo in a field name.
{ 'item.product': 'Milk Coffee' }(missing an s) gives no error, it just finds nothing. When you save data, a misspelt field name creates a new field instead, also with no error. - Misspelling the answers in the exercise. Return the exact lowercase text:
"collection","document","field","index", and"$lookup"with its$sign.
TL;DR: MongoDB is a document database: data is stored as documents shaped like JSON objects (BSON on disk) and grouped in collections. Each document may have different fields with no ALTER TABLE. The terms: a table becomes a collection, a row a document, a column a field, JOIN becomes $lookup, an index stays an index, the primary key is _id. find() takes filters, for example { total: { $gt: 750 } } (a total greater than 750). Other operators are $eq (equal to) and $in (one of a list). Dot notation ('items.product') reaches into documents inside documents (embedded documents) and arrays. Embed data that is read together and rarely changes on its own (copy it into the document). Reference data that stands alone or grows without limit (keep only its _id). Data embedded in many documents has to be changed with updateMany, because updateOne only changes the first match.
⚡ One order, one document
Write:
cafe> db.orders.findOne({ _id: 1 })
{
_id: 1,
customer: { _id: 1, name: 'Budi' },
items: [
{ product: 'Milk Coffee', price: 450, qty: 2 },
{ product: 'Toast', price: 500, qty: 1 }
],
total: 1400
}
Meaning: MongoDB stores data as documents shaped like JSON objects. Documents of the same kind are grouped in a collection, like rows in an SQL table. In mongosh (MongoDB's command-line program, prompt cafe>), findOne({ _id: 1 }) fetches order #1. One read gets everything: the buyer (customer) and the things bought (items). Each document may have different fields.
In the exercise, the terms are: a table becomes "collection", a row "document", a column "field", JOIN becomes "$lookup".
⚡ Searching with find()
Write:
cafe> db.orders.find({ total: { $gt: 750 } })
// orders #1 (1400) and #3 (825)
Meaning: find() takes a filter: an object naming a field and its condition. $gt means greater than, so the result is the orders whose total is above 750. $in matches when the value is one of a list. Dot notation ('items.product', the field product inside items) reaches into documents inside documents (embedded documents) and arrays.
⚡ Embed or reference
Guess first: Budi's name is copied (embedded) into orders #1 and #2. After updateOne changes his name, how many orders carry the new name?
Only 1. updateOne stops at the first matching document, so Budi now has two names. The right call is updateMany, which changes every match.
Meaning: Embed data that is read together and rarely changes on its own: copy it into the document. Reference data that stands alone or grows without limit: keep only its _id, like a foreign key.