0

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 the array with the width and height.

I am trying to create an aggregation query. For example for the given documents above, it 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.

1 Answer 1

1
  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

Sign up to request clarification or add additional context in comments.

Comments

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.