Search⌘ K
AI Features

Solution: Nested Queries and Fields

The topic discusses the use of nested queries in MongoDB to filter documents within a products collection. It explains the application of logical operators like $and and $or to combine multiple conditions, such as matching categories, price ranges, and stock levels. The content illustrates how to construct complex queries that require specific criteria to be met, enabling effective retrieval of documents based on defined parameters. Additionally, it highlights the importance of comparison operators for filtering based on numeric or date fields.

We'll cover the following...
Query
db.products.find(
{
$and: [
{
$or: [
{ category: "Accessories" },
{ category: "Audio" },
{ category: "Cables" }
]
},
{
$or: [
{
$and: [
{ price: { $lt: 12 } },
{ stock: { $gte: 50 } }
]
},
{
$and: [
{ price: { $gte: 20, $lte: 30 } },
{ rating: { $gte: 3.5 } }
]
}
]
}
]
}, {_id:0, name:1, category:1, brand:1, price: 1, stock:1, rating: 1}
)

The explanation of the query is given below:

  • Line 1: Start querying the products collection using the find() method to retrieve documents that match the filter object provided.

  • Line 3: Logical AND operator ensures ...