Menu Docs

Página inicial do DocsDesenvolver aplicaçõesManual do MongoDB

$push (agregação)

Nesta página

  • Definição
  • Sintaxe
  • Exemplos
$push

$push retorna uma array de todos os valores resultantes da aplicação de uma expressão a documentos.

$push está disponível nestes estágios:

$push sintaxe:

{ $push: <expression> }

Para mais informações sobre expressões, consulte Operadores de Expressão.

Considere uma collection sales com os seguintes documentos:

{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }
{ "_id" : 6, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-15T12:05:10Z") }
{ "_id" : 7, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T14:12:12Z") }

Agrupando os documentos por dia e ano do campo date , a operação a seguir usa o acumulador $push para calcular a lista de itens e as quantidades vendidas de cada grupo:

db.sales.aggregate(
[
{ $sort: { date: 1, item: 1 } },
{
$group:
{
_id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
itemsSold: { $push: { item: "$item", quantity: "$quantity" } }
}
}
]
)

A operação retorna os seguintes resultados:

{
"_id" : { "day" : 46, "year" : 2014 },
"itemsSold" : [
{ "item" : "abc", "quantity" : 10 },
{ "item" : "xyz", "quantity" : 10 },
{ "item" : "xyz", "quantity" : 5 },
{ "item" : "xyz", "quantity" : 10 }
]
}
{
"_id" : { "day" : 34, "year" : 2014 },
"itemsSold" : [
{ "item" : "jkl", "quantity" : 1 },
{ "item" : "xyz", "quantity" : 5 }
]
}
{
"_id" : { "day" : 1, "year" : 2014 },
"itemsSold" : [ { "item" : "abc", "quantity" : 2 } ]
}

Novidades na versão 5.0.

Crie uma collection cakeSales que contenha vendas de bolo nos estados da Califórnia (CA) e de Washington (WA):

db.cakeSales.insertMany( [
{ _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),
state: "CA", price: 13, quantity: 120 },
{ _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),
state: "WA", price: 14, quantity: 140 },
{ _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),
state: "CA", price: 12, quantity: 145 },
{ _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),
state: "WA", price: 13, quantity: 104 },
{ _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),
state: "CA", price: 41, quantity: 162 },
{ _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),
state: "WA", price: 43, quantity: 134 }
] )

Este exemplo usa $push no estágio $setWindowFields para gerar uma array de valores das vendas de bolos quantity para cada state:

db.cakeSales.aggregate( [
{
$setWindowFields: {
partitionBy: "$state",
sortBy: { orderDate: 1 },
output: {
quantitiesForState: {
$push: "$quantity",
window: {
documents: [ "unbounded", "current" ]
}
}
}
}
}
] )

No exemplo:

  • partitionBy: "$state" particiona os documentos na collection por state. Existem partições para CA e WA.

  • sortBy: { orderDate: 1 } classifica os documentos em cada partição por orderDate em ordem crescente (1), para que o orderDate mais antigo seja o primeiro.

  • output define a array de valores quantity usando $push para os documentos em uma janela Documentos .

    A janela contém documentos entre um limite inferior unbounded e o documento current na saída. Isso significa que $push acrescenta os valores quantity à array quantitiesForState dos documentos entre o início da partição e o documento atual.

Nessa saída, a array de valores quantity para CA e WA é mostrada na array quantitiesForState:

{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),
"state" : "CA", "price" : 41, "quantity" : 162, "quantitiesForState" : [ 162 ] }
{ "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),
"state" : "CA", "price" : 13, "quantity" : 120, "quantitiesForState" : [ 162, 120 ] }
{ "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),
"state" : "CA", "price" : 12, "quantity" : 145, "quantitiesForState" : [ 162, 120, 145 ] }
{ "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),
"state" : "WA", "price" : 43, "quantity" : 134, "quantitiesForState" : [ 134 ] }
{ "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),
"state" : "WA", "price" : 13, "quantity" : 104, "quantitiesForState" : [ 134, 104 ] }
{ "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),
"state" : "WA", "price" : 14, "quantity" : 140, "quantitiesForState" : [ 134, 104, 140 ] }
← $pow (agregação)