Search⌘ K
AI Features

Solution: Nested Queries and 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 that both conditions inside this array must be true for a document to be included in the results.

  • Lines 5–9: These use $or to match documents where the category field is either “Accessories,” “Audio,” or “Cables.” A product needs to belong to at least one of these categories. ...