Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Database › Scaling and distribution

NoSQL and the document model

Split an order into three tables, or put it in one document?

Why it exists — A relational database splits data into separate tables, so showing one order requires joining several tables, and even to add a new item you must first change the table structure. A NoSQL database such as a document database stores the data that is read together as one document and accepts documents of different shapes, which makes reads simpler and lets you add items without a structure change.

Where it's used today — Use a document database such as MongoDB for data that is read and written as one block and whose shape changes often, such as a product list where each product has different attributes, logs and event records, and per-user settings. Data that several places share and change often, such as a product name, and payment and inventory data that must change several tables at once, mostly stay in a relational database.

Store the same data (orders and order items) in two ways. The relational way splits products, orders, and order items into three tables and joins them when reading. The document model is the way used by document databases such as MongoDB: it treats one order as one document and puts the array of items and even the product names inside it.

Checked against real execution · All 20 combinations were checked by execution: the relational model on MySQL 8.4.11, and the document model on both a MySQL 8.4.11 JSON column and MongoDB 8.0.38

Concepts in this lab

NoSQL
A general name for databases that do not use the relational model. They include key-value stores (Redis), document databases (MongoDB), wide-column stores (Cassandra), and graph databases. Many are designed to store data flexibly without a fixed schema and to scale out easily across several servers, but joins and complex transactions are more limited than in relational databases.
Document model (document database)
A way of storing data in units called documents, instead of rows and columns. A document usually has a JSON-like shape, and a value in it can hold an array or another object. So data that is read together, such as an order and its items, can be kept in one document and read in one go without a join. MongoDB is the best-known document database. If you copy the same value into several documents, you must fix every copy when the value changes, so deciding what goes inside a document and what is kept separately is the heart of the design.
Fixed schema and flexible schema
A schema is the structure that decides what items the data is made of and what data type each item has. A relational database decides the columns first when a table is created and accepts only rows that fit that structure, and changing the structure requires running ALTER TABLE. A document database can usually store documents even when their items differ, and this is called a flexible schema. The structure is easy to change, but a wrong name or a missing field is also stored as it is, so keeping the shape right is left to the application code or to a validation feature that you turn on separately.
Normalization and denormalization
Normalization is the design process of splitting tables so that the same data is not stored redundantly in several places. With redundancy, a change may be made in only one place, and the data then becomes inconsistent. Denormalization intentionally allows redundancy or merges tables for read performance. It reduces joins, but it adds the burden of updating the redundant data together.
JOIN (INNER, OUTER)
The operation that combines rows of two tables according to a condition. INNER JOIN includes only the rows where the condition matches on both sides. LEFT OUTER JOIN includes every row of the left table and fills in NULL when there is no match on the right. Choose between them based on whether data without a match must stay in the result.

Try these

Running with the default settings

  1. The data is stored with the document model. The order_doc table has 3 documents, and one document is one order. Each document holds the person who ordered and the array of items (items) as a whole, and the product name is copied into each item.
  2. UPDATE order_doc SET doc = JSON_SET(…) WHERE …: It finds every document whose items array contains 'keyboard' and changes the name at that position in each document. The number of documents changed is 3. Because the product name is copied into every order document, you have to change as many documents as contain that product.
  3. This time all 3 were changed, so every order shows the new name. But if you stop after changing only some, the same product is left with different names in different documents. The database does not know that these values must be the same.

Result of this run

Code

-- The document model, reproduced with a MySQL JSON column. One row is one document
CREATE TABLE order_doc (id INT PRIMARY KEY, doc JSON NOT NULL);
-- Example of a document (order 1)
-- {"member": "kim",
--  "items": [{"product_id": 1, "name": "keyboard", "qty": 1},
--            {"product_id": 2, "name": "mouse", "qty": 2}]}

-- In each document, find the position of 'keyboard' in the items array and change the name at that position
UPDATE order_doc
SET doc = JSON_SET(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'keyboard', NULL, '$.items[*].name')), 'mechanical keyboard')
WHERE JSON_SEARCH(doc, 'one', 'keyboard', NULL, '$.items[*].name') IS NOT NULL;

-- The commands that do the same thing in MongoDB, a document database (mongosh. In the order_doc collection, one document is one order)
-- db.order_doc.updateMany(
--   { "items.name": "keyboard" },
--   { $set: { "items.$[it].name": "mechanical keyboard" } },
--   { arrayFilters: [{ "it.name": "keyboard" }] })

Assumptions of this model

On the screen, the document model is reproduced with a MySQL JSON column, and I also ran the same operations on MongoDB, a dedicated document database. I ran twenty combinations (two ways of storing, four things to do, and 2, 3, and 5 orders) with the same statements as on the screen on MySQL 8.4.11 in our test run, and checked that the following matched the screen: the error code; the number of tables and the number of result rows shown by EXPLAIN; the number of rows (documents) changed by UPDATE; the number of documents with gift; and the quantity total. I ran the ten combinations of the document model again on MongoDB 8.0.38 (the official mongo:8.0 image on Docker Hub, mongosh 2.14.3) with the commands written as comments below the code (find, updateMany with arrayFilters, insertOne, and $unwind with $group), and all three columns of the results table matched the screen. When one order was read by _id, the query plan had no join stage and only 1 document was examined; the number of documents changed by updateMany (modifiedCount) equaled the number of orders; and the document with a misspelled field name went in without an error, and $sum skipped that document. I also confirmed the following facts used in the explanations by execution. Reading without a join needs three queries, one for each table. After a column is added with ALTER TABLE, the same INSERT goes in, and the existing rows also get that column. If only one document is changed, the same product is left with two different names (on both MySQL and MongoDB). After a JSON_SCHEMA_VALID constraint is added, a document with a misspelled field name is rejected with error 3819. On MongoDB, after a $jsonSchema validation rule was added to the collection, the same document was rejected with error 121 (Document failed validation). I also saw where the two products differ. When gift is read from a document that has no gift, the MySQL JSON column gives NULL, and in MongoDB the document does not have that field at all (reading it in mongosh gives undefined). MongoDB also has the $lookup stage, which joins another collection, so a document that keeps only product_id without a copy of the product name could be read together with the product collection. MongoDB is the only document database I ran, and query syntax, how to change a value inside an array, the schema validation feature, and support for transactions and joins across several documents differ by product and version. Which way is faster depends on the data volume, the indexes, and the product, so it is not covered, and the results on the screen are the number of places read or changed, not the speed. Other kinds of NoSQL, such as key-value stores, wide-column stores, and graph databases, are not covered.

Previous lab: Redis single-threaded execution

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these