Normalization and denormalization help organize data in a database. Normalization keeps data clean and avoids repetition. Denormalization stores data together to make reading faster.
0
0
Normalization vs denormalization default in MongoDB
Introduction
When you want to avoid repeating the same data in many places.
When you need to update data easily without mistakes.
When you want to speed up reading data by storing related info together.
When your app reads data more often than it changes.
When you want to save storage space by not duplicating data.
Syntax
MongoDB
Normalization: Store related data in separate collections and link them using references. Denormalization: Store related data together in the same document by embedding.
Normalization uses references between collections.
Denormalization uses embedded documents inside one collection.
Examples
Users and orders are in different collections. Orders refer to users by ID.
MongoDB
// Normalization example // Separate collections for users and orders { _id: ObjectId("user1"), name: "Alice" } { _id: ObjectId("order1"), userId: ObjectId("user1"), product: "Book" }
Orders are stored inside the user document for faster reading.
MongoDB
// Denormalization example // Embed orders inside user document { _id: ObjectId("user1"), name: "Alice", orders: [ { product: "Book" }, { product: "Pen" } ] }
Sample Program
This shows normalized data with separate collections. The query joins orders with users to get user names.
MongoDB
// Normalization: Insert user and order separately use shopDB; db.users.insertOne({ _id: "user1", name: "Alice" }); db.orders.insertOne({ _id: "order1", userId: "user1", product: "Book" }); // Query: Find orders with user name const orders = db.orders.aggregate([ { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }, { $unwind: "$user" }, { $project: { product: 1, userName: "$user.name" } } ]).toArray(); printjson(orders);
OutputSuccess
Important Notes
Normalization reduces data duplication but can make queries slower because of joins.
Denormalization speeds up reads but can cause data duplication and harder updates.
MongoDB defaults to denormalization by embedding data inside documents.
Summary
Normalization separates data into collections linked by references.
Denormalization stores related data together inside documents.
Choose normalization for easy updates, denormalization for fast reads.