0
0
MongoDBquery~30 mins

Attribute pattern for variable fields in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Attribute Pattern for Variable Fields in MongoDB
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use a list comprehension and dict.get() to safely access nested keys.