Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ] }Advertisements