0
0
MongoDBquery~30 mins

Combining logical and comparison operators in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Combining Logical and Comparison Operators in MongoDB Queries
📖 Scenario: You are managing a small online bookstore database. You want to find books that meet certain conditions to help with marketing and stock decisions.
🎯 Goal: Build a MongoDB query that uses both logical and comparison operators to find books that are either priced below $20 and have more than 50 copies in stock, or are authored by 'Jane Austen'.
📋 What You'll Learn
Create a collection named books with specific book documents.
Add a variable priceLimit set to 20.
Write a MongoDB query using $or, $and, $lt, $gt, and $eq operators.
Complete the query to find books matching the conditions described.
💡 Why This Matters
🌍 Real World
Filtering products or items in a database based on multiple conditions is common in e-commerce, inventory management, and reporting.
💼 Career
Knowing how to combine logical and comparison operators in queries is essential for database developers, data analysts, and backend engineers.
Progress0 / 4 steps
1
Create the books collection with sample documents
Create a MongoDB collection called books and insert these exact documents: { title: 'Pride and Prejudice', author: 'Jane Austen', price: 15, stock: 30 }, { title: '1984', author: 'George Orwell', price: 18, stock: 60 }, { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', price: 22, stock: 80 }, { title: 'Emma', author: 'Jane Austen', price: 25, stock: 40 }.
MongoDB
Need a hint?

Use db.books.insertMany([...]) with the exact documents inside the array.

2
Set the price limit variable
Create a variable called priceLimit and set it to the number 20.
MongoDB
Need a hint?

Use const priceLimit = 20; to create the variable.

3
Write the MongoDB query with logical and comparison operators
Write a MongoDB query called query that uses $or with two conditions: one is an $and combining price less than priceLimit and stock greater than 50, the other is author equal to 'Jane Austen'.
MongoDB
Need a hint?

Use $or with an array containing an $and condition and an $eq condition for author.

4
Complete the query by running it on the books collection
Add a line to run db.books.find(query) to get the matching books.
MongoDB
Need a hint?

Use db.books.find(query); to run the query.