MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mit $sum in Mongodb aggregieren

Verwenden Sie $addToSet accumulator und dann $size Operator, um die Anzahl der eindeutigen projectId zu zählen

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" }}}
])