Skip to content

Clarify when $elemMatch is not necessary #2058

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions source/reference/operator/query/elemMatch.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ for :query:`$elemMatch`.
Examples
--------

Element Match
~~~~~~~~~~~~~
Primitive type element match
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Given the following documents in the ``scores`` collection:

Expand Down Expand Up @@ -87,6 +87,24 @@ Specifically, the query matches the following document:

{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }


Single embedded document field
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you only want to find documents with an array containing one (as
opposed to multiple) embedded document fields that satisfy a condition,
then ``$elemMatch`` is not necessary, and you can just write ``array.field``:

db.survey.find(
{ results: { $elemMatch: { product: "xyz" } } }
)

is equivalent to:

db.survey.find(
{ "results.product": "xyz" } } }
)

For more information on querying arrays, see
:ref:`read-operations-arrays`, including
:ref:`specify-multiple-criteria-for-array-elements` and
Expand Down