Zip two arrays and create new array of object in a reshaped form with MongoDB


For this, use aggregate along with $zip. The zip is used to transpose an array. Let us create a collection with documents −

> db.demo339.insertOne({Id:101,Score1:["98","56"],Score2:[67,89]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e529ee5f8647eb59e5620a2")
}

Display all documents from a collection with the help of find() method −

> db.demo339.find();

This will produce the following output −

{ "_id" : ObjectId("5e529ee5f8647eb59e5620a2"), "Id" : 101, "Score1" : [ "98", "56" ], "Score2" : [ 67, 89 ] }

Following is the query to zip two arrays with $zip and create a new array of object −

> db.demo339.aggregate([
...    {
...       "$project": {
...          "AllArrayObject": {
...             "$map": {
...                "input": {
...                   "$objectToArray": {
...                      "$arrayToObject": {
...                         "$zip": {
...                            "inputs": [
...                               "$Score1",
...                               "$Score2"
...                            ]
...                         }
...                      }
...                   }
...                },
.
...                "as": "el",
...                "in": {
...                   "Score1": "$$el.k",
...                   "Score2": "$$el.v"
...                }
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e529ee5f8647eb59e5620a2"), "AllArrayObject" : [ { "Score1" : "98", "Score2" : 67 }, { "Score1" : "56", "Score2" : 89 } ] }

Updated on: 02-Apr-2020

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements