MongoDB Concepts — Database

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…

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
}

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)

Embed or reference

There are two ways to store related data:

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

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

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.

What you will learn