Home > Mobile >  MongoDB Aggregation: How to group in Array value?
MongoDB Aggregation: How to group in Array value?

Time:07-22

For Example, Documents.

[
  {
    "username": "joy",
    "size_info": [
      {
        "size": "M",
        "width": 100,
        "height": 102
      },
      {
        "size": "M",
        "width": 102,
        "height": 104
      },
      {
        "size": "S",
        "width": 80,
        "height": 82
      }
    ]
  }
]

I want to group size_info.size and push array the width and height.

I am trying to create an aggregation. For example for the given documents above, I would look like below:


[
  {
    "username": "joy",
    "size_info": [
      {
        "size": "M",
        "actual_size": [
          {
            "width": 100,
            "height": 102
          },
          {
            "width": 102,
            "height": 104
          }
        ]
      },
      {
        "size": "S",
        "actual_size": [
          {
            "width": 80,
            "height": 82
          }
        ]
      }
    ]
  }
]

Is it possible? thank you for helping

CodePudding user response:

  1. $unwind - Deconstruct size_info array into multiple documents.

  2. $group - Group by username and size_info.size. Add the documents into actual_size array.

  3. $group - Group by username. Add the documents into size_info array.

  4. $project - Decorate the output documents.

db.collection.aggregate([
  {
    $unwind: "$size_info"
  },
  {
    $group: {
      _id: {
        username: "$username",
        size: "$size_info.size"
      },
      actual_size: {
        $push: {
          width: "$size_info.width",
          height: "$size_info.height"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id.username",
      size_info: {
        $push: {
          size: "$_id.size",
          actual_size: "$actual_size"
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      username: "$_id",
      size_info: 1
    }
  }
])

Sample Mongo Playground

  • Related