0
0
MongoDBquery~30 mins

Unique index behavior in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Unique Index Behavior in MongoDB
📖 Scenario: You are managing a small online store database using MongoDB. You want to ensure that each product has a unique product code so that no two products can have the same code. This helps avoid confusion when customers order products.
🎯 Goal: Create a MongoDB collection called products with some initial product documents. Then, add a unique index on the product_code field to prevent duplicate product codes. Finally, insert a new product and observe how the unique index enforces uniqueness.
📋 What You'll Learn
Create a products collection with three product documents having product_code and name fields.
Create a unique index on the product_code field in the products collection.
Try to insert a new product with a product_code that already exists and observe the error.
Insert a new product with a unique product_code successfully.
💡 Why This Matters
🌍 Real World
Unique indexes are used in real databases to ensure data integrity, such as preventing duplicate user emails or product codes.
💼 Career
Database administrators and backend developers often create unique indexes to enforce business rules and avoid data duplication.
Progress0 / 4 steps
1
Create the products collection with initial data
Create a MongoDB collection called products and insert these three documents exactly: { product_code: "P001", name: "Notebook" }, { product_code: "P002", name: "Pen" }, and { product_code: "P003", name: "Eraser" }.
MongoDB
Need a hint?

Use db.products.insertMany() with an array of product documents.

2
Create a unique index on product_code
Create a unique index on the product_code field in the products collection using db.products.createIndex() with the option { unique: true }.
MongoDB
Need a hint?

Use db.products.createIndex({ product_code: 1 }, { unique: true }) to create the unique index.

3
Try inserting a product with a duplicate product_code
Try to insert a new product document { product_code: "P002", name: "Marker" } into the products collection. This should fail because product_code "P002" already exists and the unique index prevents duplicates.
MongoDB
Need a hint?

Use db.products.insertOne({ product_code: "P002", name: "Marker" }) to try inserting the duplicate.

4
Insert a product with a unique product_code
Insert a new product document { product_code: "P004", name: "Ruler" } into the products collection. This should succeed because product_code "P004" is unique.
MongoDB
Need a hint?

Use db.products.insertOne({ product_code: "P004", name: "Ruler" }) to insert the unique product.