Suppose a collection contains the following 3 documents:
[
{ "_id": 1, "prop": 1 },
{ "_id": 2, "prop": 4 },
{ "_id": 3, "prop": [1, 2, 3] }
]
The query { $match: { prop: 1 } }
returns 2 documents, namely 1 and 3. I would have expected it to only return 1.
- Is this behaviour documented somewhere or is it a bug?
- How could one formulate the query to mean strict equality (as opposed to equality or array-contains)?
2
Answers
I think that MongoDB will always try to match against both scalars and arrays, unless you explicitly rule out the latter:
It doesn’t seem to be explicitly documented, but it’s implied in the documentation because the syntax for querying scalars for a particular value is the same as the syntax for querying arrays.
_id: 3
is due to Query an Array for an Element.The document with
_id: 3
will be fulfilled as there is an element matched in the array.