bihari atal
bihari atal

Reputation: 1

merge two fields in mongodb

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

Upvotes: 0

Views: 176

Answers (1)

ray
ray

Reputation: 15227

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.

Upvotes: 1

Related Questions