Definição
$elemMatchThe
$elemMatchoperator limits the contents of an<array>field from the query results to contain only the first element matching the$elemMatchcondition.
Considerações de uso
Elemento retornado
Both the $ operator and the $elemMatch operator project the first matching element from an array based on a condition.
O operador $ projeta o primeiro elemento de array correspondente de cada documento em uma collection com base em alguma condição da declaração de query.
The $elemMatch projection operator takes an explicit condition argument. This allows you to project based on a condition not in the query, or if you need to project based on multiple fields in the array's embedded documents. See Array Field Limitations for an example.
Ordem do campo
Regardless of the ordering of the fields in the document, the $elemMatch projection of an existing field returns the field after the other existing field inclusions.
Por exemplo, considere uma collection players com o seguinte documento:
db.players.insertOne( { name: "player1", games: [ { game: "abc", score: 8 }, { game: "xyz", score: 5 } ], joined: new Date("2020-01-01"), lastLogin: new Date("2020-05-01") } )
A projeção a seguir retorna o campo games após os outros campos existentes incluídos na projeção, embora no documento o campo esteja listado antes dos campos joined e lastLogin:
db.players.find( {}, { games: { $elemMatch: { score: { $gt: 5 } } }, joined: 1, lastLogin: 1 } )
Ou seja, a operação retorna o seguinte documento:
{ "_id" : ObjectId("5edef64a1c099fff6b033977"), "joined" : ISODate("2020-01-01T00:00:00Z"), "lastLogin" : ISODate("2020-05-01T00:00:00Z"), "games" : [ { "game" : "abc", "score" : 8 } ] }
Restrições
db.collection.find()operations on views do not support$elemMatchprojection operator.You cannot specify a
$textquery operator in an$elemMatch.
Exemplos
The examples on the $elemMatch projection operator assumes a collection schools with the following documents:
{ _id: 1, zipcode: "63109", students: [ { name: "john", school: 102, age: 10 }, { name: "jess", school: 102, age: 11 }, { name: "jeff", school: 108, age: 15 } ] }, { _id: 2, zipcode: "63110", students: [ { name: "ajax", school: 100, age: 7 }, { name: "achilles", school: 100, age: 8 }, ], athletics: [ "swimming", "basketball", "football" ] }, { _id: 3, zipcode: "63109", students: [ { name: "ajax", school: 100, age: 7 }, { name: "achilles", school: 100, age: 8 }, ], athletics: [ "baseball", "basketball", "soccer" ] }, { _id: 4, zipcode: "63109", students: [ { name: "barney", school: 102, age: 7 }, { name: "ruth", school: 102, age: 16 }, ] }
Pesquisa de CEP
The operation returns the following documents that have a zipcode value of "63109" and projects the students array using $elemMatch:
{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] } { "_id" : 3 } { "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }
For the document with
_idequal to1, thestudentsarray contains multiple elements with theschoolfield equal to102. However, the$elemMatchprojection returns only the first matching element from the array.The document with
_idequal to3does not contain thestudentsfield in the result since no element in itsstudentsarray matched the$elemMatchcondition.
$elemMatch com vários campos
The $elemMatch projection can specify criteria on multiple fields.
A operação retorna os três documentos que têm um valor zipcode de "63109":
{ "_id" : 1, "students" : [ { "name" : "jess", "school" : 102, "age" : 11 } ] } { "_id" : 3 } { "_id" : 4, "students" : [ { "name" : "ruth", "school" : 102, "age" : 16 } ] }
The document with _id equal to 3 does not contain the students field since no array element matched the $elemMatch criteria.
The argument to $elemMatch matches elements of the array that $elemMatch is projecting. If you specify an equality with a field name to $elemMatch, it attempts to match objects within the array. For example, $elemMatch attempts to match objects, instead of scalar values, within the array for the following in the projection:
Os exemplos anteriores retornam os documentos que têm um valor de zipcode "63109", mas esses documentos incluem apenas o campo _id porque a operação de projeção não encontrou elementos correspondentes.
A operação retorna os três documentos que têm o valor zipcode de "63109". Os documentos retornados incluem o campo _id e os elementos correspondentes da array athletics, se existirem.
[ { _id: 1 }, { _id: 3, athletics: [ 'basketball' ] }, { _id: 4 } ]
The document with _id equal to 3 is the only document that matched the $elemMatch criteria.
Dica
$ (projection) operador, operador