Tasneem Desai
Tasneem Desai

Reputation: 21

group by id final result in mongodb

currently i am getting below response

[
    {
        "_id": "89787517-0085-3a0a-7232-1105457d6075",
        "totalStoriesPlanned": 2,
        "storiesWithDependencies": 0,
        "plannedVelocity": null,
        "actualVelocity": 0,
        "businessValue": 0,
        "sprintType": "Dev",
        "storyData": [],
        "teamExternalId": "b663fa97-22fa-44b9-b845-22a57d408550"
    }
{
        "_id": "12347517-0085-3a0a-7232-1105457d6075",
        "totalStoriesPlanned": 2,
        "storiesWithDependencies": 0,
        "plannedVelocity": null,
        "actualVelocity": 0,
        "businessValue": 0,
        "sprintType": "Dev",
        "storyData": [],
        "teamExternalId": "b663fa97-22fa-44b9-b845-22a57d408550"
    }

]

i want response like below. group by teamExternalId:

{
   "teamExternalId": "b663fa97-22fa-44b9-b845-22a57d408550",
   "insight":[
    {
        "_id": "89787517-0085-3a0a-7232-1105457d6075",
        "totalStoriesPlanned": 2,
        "storiesWithDependencies": 0,
        "plannedVelocity": null,
        "actualVelocity": 0,
        "businessValue": 0,
        "sprintType": "Dev",
        "storyData": [],
        "teamExternalId": "b663fa97-22fa-44b9-b845-22a57d408550"
    },
{
        "_id": "12347517-0085-3a0a-7232-1105457d6075",
        "totalStoriesPlanned": 2,
        "storiesWithDependencies": 0,
        "plannedVelocity": null,
        "actualVelocity": 0,
        "businessValue": 0,
        "sprintType": "Dev",
        "storyData": [],
        "teamExternalId": "b663fa97-22fa-44b9-b845-22a57d408550"
    }


]


}

Upvotes: 0

Views: 37

Answers (1)

NeNaD
NeNaD

Reputation: 20354

You can do it like this:

  • group - to group documents by teamExternalId field
  • project - to project fields in requested format
db.collection.aggregate([
  {
    "$group": {
      "_id": "$teamExternalId",
      "insight": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      "teamExternalId": "$_id",
      "_id": 0,
      "insight": 1
    }
  }
])

Working example

Upvotes: 1

Related Questions