0

I used unwind aggregation but I am with an error I need output like. the remaining data is also in the same format

[
  {
    "_id": "767",
    "customId": [
      "growth",
      "fine"
    ],
    "length": [
      1526,
      95
    ]
  },
  {
    "_id": "66",
    "customId": [
      "height",
      "good"
    ],
    "length": [
      86,
      68
    ]
  }
]

I used unwind aggregation but I am with an error I need output like. the remaining data is also in the same format

[
  {
    "_id": "767",
    "merged": [
      {
        "customId": "growth",
        "length": 1526
      },
      {
        "customId": "fine",
        "length": 95
      }
    ]
  },
  {
    "_id": "66",
    "merged": [
      {
        "customId": "height",
        "length": 86
      },
      {
        "customId": "good",
        "length": 68
      }
    ]
  }
]

I am using postman to know whether it is working or not

1 Answer 1

1

You can use $zip to construct pairs from the 2 arrays and use $arrayElemAt to wrangle to your expected output.

db.collection.aggregate([
  {
    "$project": {
      merged: {
        "$zip": {
          "inputs": [
            "$customId",
            "$length"
          ]
        }
      }
    }
  },
  {
    "$project": {
      merged: {
        "$map": {
          "input": "$merged",
          "as": "m",
          "in": {
            "customId": {
              "$arrayElemAt": [
                "$$m",
                0
              ]
            },
            "length": {
              "$arrayElemAt": [
                "$$m",
                1
              ]
            }
          }
        }
      }
    }
  }
])

Here is the Mongo Playground for your reference.

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.