$ cada
Nesta página
Definição
$each
The
$each
modifier is available for use with the$addToSet
operator and the$push
operator.Use with the
$addToSet
operator to add multiple values to an array<field>
if the values do not exist in the<field>
.{ $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } } } Use with the
$push
operator to append multiple values to an array<field>
.{ $push: { <field>: { $each: [ <value1>, <value2> ... ] } } } The
$push
operator can use$each
modifier with other modifiers. For a list of modifiers available for$push
, see Modifiers.
Comportamento
A partir do MongoDB 5.0, os operadores de atualização processam campos de documento com nomes baseados em cadeia de caracteres em ordem lexicográfica. Os campos com nomes numéricos são processados em ordem numérica. Consulte Atualizar Comportamento de Operadores para detalhes.
Exemplos
Usar $each
with $push
Operator
The following example appends each element of [ 90, 92, 85 ]
to
the scores
array for the document where the name
field
equals joe
:
db.students.updateOne( { name: "joe" }, { $push: { scores: { $each: [ 90, 92, 85 ] } } } )
Usar $each
with $addToSet
Operator
Uma collection inventory
possui o seguinte documento:
{ _id: 2, item: "cable", tags: [ "electronics", "supplies" ] }
Then the following operation uses the $addToSet
operator
with the $each
modifier to add multiple elements to the
tags
array:
db.inventory.updateOne( { _id: 2 }, { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } } )
A operação só adiciona "camera"
e "accessories"
à array tags
. "electronics"
já estava na array:
{ _id: 2, item: "cable", tags: [ "electronics", "supplies", "camera", "accessories" ] }