Rajat
Rajat

Reputation: 526

Aggregate with $sum in mongodb

I have data in worksheets collection like below:

/* 1 */
{
    "_id" : ObjectId("5c21d780f82aa31334ab6506"),
    "isBilling" : true,
    "hours" : 6,
    "userId" : ObjectId("5c1f38a1d7537d1444738467"),
    "projectId": ObjectId("5c1f38a1d7537d1444731234");
}

/* 2 */
{
    "_id" : ObjectId("5c21d780f82aa31334ab6507"),
    "isBilling" : true,
    "hours" : 4,
    "userId" : ObjectId("5c1f38a1d7537d1444738493"),
    "projectId": ObjectId("5c1f38a1d7537d1444734567");
}

/* 3 */
{
    "_id" : ObjectId("5c21e10fae07cc1204a5b647"),
    "isBilling" : false,
    "hours" : 8,
    "userId" : ObjectId("5c1f388fd7537d1444738492"),
    "projectId": ObjectId("5c1f38a1d7537d1444731234");
}

I am using below aggregate query to get total count of fields:

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

Now i want the sum of unique projectId field. It above case it is 2. I tried it by applying two $group in above implemented query. But it is not working. I want to get the result like below:

[
  {
    "_id": null,
    "billingHours": 0,
    "fixContract": 8,
    "totalProjects": 2
  }
]

Upvotes: 1

Views: 95

Answers (1)

Ashh
Ashh

Reputation: 46491

Use $addToSet accumulator and then $size operator to count the number of unique projectId

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

Upvotes: 1

Related Questions