Rajat
Rajat

Reputation: 526

Use Aggregate with $group in mongodb

I have data in worksheets collection like below:

/* 1 */
{
    "_id" : ObjectId("5c21d780f82aa31334ab6506"),
    "isBilling" : true,
    "hours" : 6,
    "userId" : ObjectId("5c1f38a1d7537d1444738493"),
}

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

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

I have to create a aggregate query to sum the hours, where isBilling equals to true, and where isBilling equals to false.I want the below output:

{
 "billingHours":10,
 "fixContract":8
}

I have to get data with the particular userId. I tried the below:

Worksheet.aggregate([
  {
        $match: conditions
  },
  {
      $lookup:{
          "from": "worksheets",
          "let": {},
          "pipeline": [
            { "$match": { "$expr": { "$eq": [ "$isBilling",false] } } },
            { 
              "$group": { "_id": null, "totalHours": { "$sum": "$hours" } }
            },
          ],
          "as": "billingHours"
      }
  },
  {
        "$project":{"billingHours":1}
  }
])

I am getting the below result:

[
    {
        "_id": "5c21d780f82aa31334ab6506",
        "billingHours": [
            {
                "_id": null,
                "totalHours": 16
            }
        ]
    },
    {
        "_id": "5c21d780f82aa31334ab6507",
        "billingHours": [
            {
                "_id": null,
                "totalHours": 16
            }
        ]
    }
]

I don't know why it is giving me 16 hours instead of 10 and giving me two objects instead of 1.

Upvotes: 1

Views: 61

Answers (1)

Ashh
Ashh

Reputation: 46441

You don't need to use $lookup here. Simple $group with $cond will do the job.

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

Upvotes: 1

Related Questions