Home > OS >  MongoDB Merge two arrays into one
MongoDB Merge two arrays into one

Time:08-09

I am writing an aggregation and have arrays of the form:

array1: [
{item:value},
{item:value},
...
]
array2: [
{price:value},
{price:value},
...
]

How can I merge them into this format:

array3: [
{item:value, price:value},
{item:value, price:value},
...
]

They are already in the proper order, so the object at index 0 for both arrays are matched up.

This seems like it should be easy to me, but the $concatArrays operator only works along the first dimension.

I have a method that works using the group stage, but it is quite slow, so I am trying to find another method.

Thanks a lot.

CodePudding user response:

You can combine the two arrays and then cycle the result using map, try something as follows:

db.collection.aggregate([
  {
    "$project": {
      array3: {
        $map: {
          input: {
            $zip: {
              inputs: [
                "$array1",
                "$array2"
              ]
            }
          },
          as: "tuple",
          in: {
            item: {
              "$arrayElemAt": [
                "$$tuple.item",
                0
              ]
            },
            price: {
              "$arrayElemAt": [
                "$$tuple.price",
                0
              ]
            }
          }
        }
      }
    }
  },
  
])

You can test it here.

  • Related