When using arrays, you can add multiple conditions that must apply to the same element.
Consider the following document:
{
"list": [
{"a": 1, "b": "red"},
{"a": 2, "b": "green"}
]
}
"list": [
{"a": 1, "b": "red"},
{"a": 2, "b": "green"}
]
}
This query might not return what you expect. It returns the document because the two conditions can refer to different array elements:
db.items.find({"list.a": 1, "list.b": "green"})
$elemMatch
to the rescue:
db.items({list: {$elemMatch: {a: 1, b: "green"}}})
This doesn't return the document, because the condition is "a single array element of the list
property must match a: 1
and b: "green"
".