MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Aggregati annuali, mensili e settimanali in MongoDB

Puoi costruire una pipeline con più $group, trasportando avanti i totali più ampi.

db.statements.aggregate([
  { $group: {
    _id: { name: "$name", year: { $year: "$date" }, month: { $month: "$date" } },
    total: { $sum: "$amount" }
  } },
  { $group: { _id: "$_id.name", totalYearly: { $sum: "$total" } } }
])

Se devi filtrare, metti $match all’inizio: $redact è più costoso e non usa indici.