📖 Scenario: You are managing a MongoDB collection for a small online store. Each product can have different attributes depending on its category. For example, electronics have brand and warranty, while clothing has size and material. You want to store these variable fields efficiently and query them.
🎯 Goal: Build a MongoDB document structure that uses an attribute pattern to store variable fields for different product categories. Then write a query to find products with a specific attribute.
📋 What You'll Learn
Create a MongoDB collection named products with documents having fixed fields _id, name, and category.
Add a variable attributes field as a sub-document to store category-specific attributes.
Write a query to find all products where the attributes contain a specific key-value pair.
💡 Why This Matters
🌍 Real World
Many real-world databases store items with different attributes depending on their type. Using an attribute pattern helps keep the data flexible and easy to query.
💼 Career
Understanding how to model variable fields and query them is important for database developers and data engineers working with NoSQL databases like MongoDB.
Progress0 / 4 steps
1
Create the products collection with sample documents
Create a variable called products that is a list of three MongoDB documents. Each document must have the fields _id, name, and category with these exact values: {'_id': 1, 'name': 'Smartphone', 'category': 'Electronics'}, {'_id': 2, 'name': 'T-Shirt', 'category': 'Clothing'}, and {'_id': 3, 'name': 'Laptop', 'category': 'Electronics'}.
MongoDB
Hint
Use a Python list with dictionaries for each product document.
2
Add the attributes field with variable data
Add an attributes field to each document in the products list. For the product with _id 1, add {'brand': 'BrandX', 'warranty': '2 years'}. For _id 2, add {'size': 'M', 'material': 'Cotton'}. For _id 3, add {'brand': 'BrandY', 'warranty': '1 year'}.
MongoDB
Hint
Add the attributes key with a dictionary value inside each product dictionary.
3
Write a MongoDB query to find products with a specific attribute
Create a variable called query that is a MongoDB query document to find all products where the attributes.brand is exactly 'BrandX'.
MongoDB
Hint
Use dot notation in the query key to access nested fields.
4
Complete the MongoDB find operation using the query
Create a variable called result that simulates the MongoDB find operation by filtering the products list using the query. Use a list comprehension to include only products where attributes.brand equals 'BrandX'.
MongoDB
Hint
Use a list comprehension and dict.get() to safely access nested keys.
Practice
(1/5)
1. In MongoDB, which operator helps you find documents where a field's value matches a text pattern?
easy
A. $match
B. $regex
C. $group
D. $project
Solution
Step 1: Understand pattern matching in MongoDB
MongoDB uses $regex to match string patterns inside field values.
Step 2: Identify the operator for text pattern search
$regex is the operator designed for regular expression matching in queries.
Final Answer:
$regex -> Option B
Quick Check:
Pattern matching = $regex [OK]
Hint: Use $regex to match text patterns in fields quickly [OK]
Common Mistakes:
Confusing $regex with $match which filters documents
Using $group which aggregates data, not filters by pattern
Using $project which reshapes documents, not filters
2. Which MongoDB aggregation stage converts a document's fields into an array of key-value pairs, useful for filtering variable field names?
easy
A. $objectToArray
B. $filter
C. $arrayToObject
D. $match
Solution
Step 1: Understand field-to-array conversion
$objectToArray converts document fields into an array of {k, v} pairs.
Step 2: Identify the correct stage for this conversion
$objectToArray is the aggregation operator that does this transformation.
Final Answer:
$objectToArray -> Option A
Quick Check:
Field to array = $objectToArray [OK]
Hint: Use $objectToArray to turn fields into key-value arrays [OK]
Common Mistakes:
Using $filter which filters arrays but doesn't convert fields
Confusing $arrayToObject which does the reverse conversion
Using $match which filters documents, not fields
3. Given this aggregation pipeline snippet, what will be the output for a document {"a1": 5, "b2": 10, "c3": 15}?
A. Incorrect order of $regex arguments; 'input' must come first
B. Missing $match stage before $project
C. Using $regex instead of $regexMatch inside $filter condition
D. Cannot use $objectToArray on $ROOT
Solution
Step 1: Check $regex usage inside $filter cond
$regex is a query operator, but inside aggregation expressions, $regexMatch must be used for regex matching.
Step 2: Identify correct regex function for aggregation
Use $regexMatch with 'input' and 'regex' keys; $regex alone is invalid here.
Final Answer:
Using $regex instead of $regexMatch inside $filter condition -> Option C
Quick Check:
Aggregation regex = $regexMatch, not $regex [OK]
Hint: Use $regexMatch, not $regex, inside aggregation expressions [OK]
Common Mistakes:
Swapping input and regex keys in $regexMatch
Trying to use $regex query operator inside aggregation
Assuming $objectToArray can't be used on $ROOT
5. You have documents with variable field names like "score_math", "score_science", "age", "name". How do you write an aggregation pipeline stage to create a new field "scores" containing only fields whose names start with "score_" and their values?