Group by nested object and group items to array

I have an array like this:

[
    {
        name: "a",
        title: {
            title: "b",
            order: 1
        },
        group: "B"
    },
    {
        name: "b",
        title: {
            title: "b",
            order: 1
        },
        group: "B"
    },
    {
        name: "c",
        title: {
            title: "c",
            order: 2
        },
        group: "B"
    }
]

How do I convert to this:

[
    {
        _id: "b",
        items: [
            {name: "a", group: "B"},
            {name: "b", group: "B"}
        ]
    },
    {
        _id: "c",
        items: [
            {name: "c", group: "B"}
        ]
    }
]

I know I can use $group operator but I only get _id field, please help me.

1 Like

Hi,

You can do it like this:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$title.title",
      "items": {
        "$addToSet": {
          "name": "$name",
          "group": "$group"
        }
      }
    }
  }
])

Working example

1 Like

Awesome, I can’t believe mongodb can do it easily like this. Thanks so much!

1 Like