Search code examples
mongodbaggregation-frameworkmongodb-compass

How to join two arrays into fields of object


In mongodb aggregate, I have below document:

{key:['a','b','c'], scores:[1,2,3]}

And want to change it to

{a:1, b:2, c:3}

How to do it in aggregate stage? I'm using MongoDB Compass Version 1.21.2 (1.21.2)


Solution

  • You can use $zip

    play

    db.collection.aggregate([
      {
        $project: {
          "output": {
            "$zip": {
              "inputs": [
                "$key",
                "$scores"
              ],
              
            }
          }
        }
      }
    ])
    

    It maps the values the way you need but the format is different.

    You can use $unwind, $project, $arrayToObject to convert further to the object structure.

    As @turivishal pointed out, you can convert the above to the desired structure using (this)[mongoplayground.net/p/PSnIzI8nF0A].