MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Aggrega con $sum in mongodb

Usa $addToSet accumulator e quindi $size operatore per contare il numero di projectId univoci

Worksheet.aggregate([
  { $match: conditions },
  { "$group": {
    "_id": null,
    "billingHours": {
      "$sum": {
        "$cond": [{ "$eq": ["$isBilling", true] }, "$hours", 0]
      }
    },
    "fixContract": {
      "$sum": {
        "$cond": [{ "$eq": ["$isBilling", true] }, 0, "$hours"]
      }
    },
    "projectIds": { "$addToSet": "$projectId" }
  }},
  { "$addFields": { "projectIds": { "$size": "$projectIds" }}}
])