- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
How to aggregate array documents in MongoDB?
For this, use the aggregate framework. Let us first create a collection with documents −
> db.aggregateArrayDemo.insertOne( { "_id":100, "UserDetails": [ { "UserName": "John", "UserLoginYear":2010 }, { "UserName": "Carol", "UserLoginYear":2019 } ] } ); { "acknowledged" : true, "insertedId" : 100 }
Following is the query to display all documents from a collection with the help of find() method −
> db.aggregateArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : 100, "UserDetails" : [ { "UserName" : "John", "UserLoginYear" : 2010 }, { "UserName" : "Carol", "UserLoginYear" : 2019 } ] }
Following is the query to aggregate array documents −
> db.aggregateArrayDemo.aggregate([ { $match: { _id: 100 } }, { $project: { Minimum: { $min: "$UserDetails.UserLoginYear" }, Maximum: { $max: "$UserDetails.UserLoginYear" } } } ]);
This will produce the following output −
{ "_id" : 100, "Minimum" : 2010, "Maximum" : 2019 }
Advertisements