0

The document has an array field and each of them has a unique Id field. After doing unwind on the array, I need to add a count field on each array document instead of Id. The count should be the sum of similar array fields (grouped by fields other than Id).

Sample document - https://mongoplayground.net/p/LUPqVw07unP

Expected result:

{
    "originId": 123,
    "taskMetric": {
        "count": 2,
        "status": "OPEN",
        "assignee": "ABC"
    }
}, {
    "originId": 1,
    "taskMetric": {
        "count": 1,
        "status": "COMPLETED",
        "assignee": "CDE"
    }
}, {
    "originId": 1,
    "taskMetric": {
        "count": 1,
        "status": "COMPLETED",
        "assignee": "EFG"
    }
}

1 Answer 1

1

Play

You have to add one more projection stage to avoid _id and add id to group stage as other fields to the following query.

db.collection.aggregate([
  {
    $unwind: "$tasks"
  },
  {
    $group: {
      "_id": {
        "status": "$tasks.status",
        "assignee": "$tasks.assignee"
      },
      "count": {
        $sum: 1
      },
      "status": {
        $first: "$tasks.status"
      },
      "assignee": {
        $first: "$tasks.assignee"
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

mongoplayground.net/p/YX8AFpFwOst - this gave me the expected. Thanks @Gibbs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.