When To Use MongoDB's $elemMatch
You have an e-commerce database. You want to find all orders where a customer bought a laptop for more than $1000. Simple query, right? db.orders.find({ "items.category": "laptop", "items.price": {...

Source: DEV Community
You have an e-commerce database. You want to find all orders where a customer bought a laptop for more than $1000. Simple query, right? db.orders.find({ "items.category": "laptop", "items.price": { $gt: 1000 } }) Except this returns orders where the customer bought any laptop AND any item over $1000 - even if the laptop itself cost $50. This is MongoDB's most common query mistake. Let's see why it happens and how to fix it. The Problem: Array Query Logic Here's sample data from an e-commerce orders collection: { _id: 1, customer: "Alice", items: [ { category: "laptop", price: 1200, name: "MacBook Pro" }, { category: "mouse", price: 25, name: "Wireless Mouse" } ] } { _id: 2, customer: "Bob", items: [ { category: "laptop", price: 500, name: "Chromebook" }, { category: "monitor", price: 1500, name: "4K Display" } ] } What you want: Orders where someone bought a laptop costing more than $1000 (Alice's order only) What this query returns: db.orders.find({ "items.category": "laptop", "items.