0
0
MongoDBquery~30 mins

Comparison expressions ($eq, $gt in aggregation) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Filtering Products with Comparison Expressions in MongoDB Aggregation
📖 Scenario: You are managing a small online store's product database. You want to find products based on their price and stock availability using MongoDB aggregation queries.
🎯 Goal: Build a MongoDB aggregation pipeline that filters products using comparison expressions $eq and $gt to find products with specific price and stock conditions.
📋 What You'll Learn
Create a collection named products with given product documents
Add a variable to specify the minimum stock threshold
Write an aggregation pipeline using $match with $eq and $gt comparison expressions
Complete the pipeline to return only products that meet the price and stock criteria
💡 Why This Matters
🌍 Real World
Filtering products in an online store database to find items matching specific price and stock conditions.
💼 Career
Understanding MongoDB aggregation with comparison expressions is essential for backend developers and data analysts working with NoSQL databases.
Progress0 / 4 steps
1
Create the products collection with sample data
Create a MongoDB collection called products and insert these exact documents: { name: "Pen", price: 5, stock: 50 }, { name: "Notebook", price: 15, stock: 20 }, { name: "Eraser", price: 3, stock: 100 }, { name: "Backpack", price: 45, stock: 10 }.
MongoDB
Need a hint?

Use db.products.insertMany([...]) with the exact product documents.

2
Set a minimum stock threshold variable
Create a variable called minStock and set it to 20 to use as the minimum stock threshold for filtering products.
MongoDB
Need a hint?

Use const minStock = 20 to define the threshold.

3
Write an aggregation pipeline using $eq and $gt
Create a variable called pipeline that contains an aggregation pipeline with a $match stage. Use $eq to filter products where price equals 15 and $gt to filter products where stock is greater than minStock.
MongoDB
Need a hint?

Use { $match: { price: { $eq: 15 }, stock: { $gt: minStock } } } inside the pipeline array.

4
Complete the aggregation query to find matching products
Use db.products.aggregate(pipeline) to run the aggregation pipeline and assign the result to a variable called result.
MongoDB
Need a hint?

Use const result = db.products.aggregate(pipeline) to run the query.