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

MongoDBDatabaseBig Data Analytics

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 } ] }
raja
Published on 02-Apr-2020 07:18:55
Advertisements