- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to unwind two arrays
To unwind, means to deconstruct an array field from the input documents to output a document for each element.
To unwind arrays, use $unwind in MongoDB aggregation. Let us first create a collection with documents −
> db.demo387.insertOne( ... { ... ... "Name" : "101", ... "Details1" : [ ... {Value:100, Value1:50, Value2:40}, ... {Value:200}, ... {Value:300} ... ], ... "Details" : [ ... {Value:100, Value1:30, Value2:26}, ... {Value:200}, ... {Value:300} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5d197022064be7ab44e7f8") }
Display all documents from a collection with the help of find() method −
> db.demo387.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : [ { "Value" : 100, "Value1" : 50, "Value2" : 40 }, { "Value" : 200 }, { "Value" : 300 } ], "Details" : [ { "Value" : 100, "Value1" : 30, "Value2" : 26 }, { "Value" : 200 }, { "Value" : 300 } ] }
Following is the query to aggregate document with more than 1 array −
> db.demo387.aggregate([ ... { "$unwind": "$Details1" }, ... { "$unwind": "$Details" }, ... { "$match": { "$expr": ... { "$eq": ["$Details1.Value", "$Details.Value"] } ... }} ... ])
This will produce the following output −
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 100, "Value1" : 50, "Value2" : 40 }, "Details" : { "Value" : 100, "Value1" : 30, "Value2" : 26 } } { "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 200 }, "Details" : { "Value" : 200 } } { "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 300 }, "Details" : { "Value" : 300 } }
- Related Articles
- Unwind two arrays from MongoDB
- MongoDB $unwind to get the count
- MongoDB query in object of arrays
- What is the $unwind operator in MongoDB?
- Implement MongoDB Aggregate - unwind, group and project?
- MongoDB query condition to compare two fields?
- How to get the intersection of two arrays in MongoDB?
- Getting unique values within two arrays in one MongoDB document
- MongoDB aggregate query to sort
- MongoDB query to calculate average
- MongoDB query to skip documents
- MongoDB query to sort subdocuments
- MongoDB query to update tag
- MongoDB query to add matched key to list after query?
- MongoDB query to set user defined variable into query?

Advertisements