Querieseasy0-2 years
A query for orders containing a line with SKU "A-1" and quantity over 5 uses `{ "lines.sku": "A-1", "lines.qty": { $gt: 5 } }` and returns an order where the SKU-A-1 line has quantity 1 and a completely different line has quantity 20. What went wrong, and what's the fix?
Dot notation into an array field doesn't test one element against both conditions together — "lines.sku": "A-1" matches an order where some line has that SKU, and "lines.qty": { $gt: 5 } matches an order where some line (possibly a different one) has a quantity over 5. MongoDB is happy to satisfy the two conditions from two different array elements, because each condition is checked against the array as a whole, independently. $elemMatch fixes this by requiring both conditions to hold on the same element: { lines: { $elemMatch: { sku: "A-1", qty: { $gt: 5 } } } } only matches when one line in the array has SKU A-1 and quantity over 5 at once.