- 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
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 }
- Related Articles
- How can I aggregate nested documents in MongoDB?
- Aggregate based on array value to sum values in different MongoDB documents?
- MongoDB aggregate to convert multiple documents into single document with an array?
- MongoDB query to aggregate nested array
- How to search documents through an integer array in MongoDB?
- How to filter documents based on an array in MongoDB?
- MongoDB Aggregate sum of values in a list of dictionaries for all documents?
- Aggregate by country, state and city in a MongoDB collection with multiple documents
- MongoDB aggregate to get the Mean daily average count of recorded documents in a collection?
- How to update after aggregate in MongoDB?
- How to find latest entries in array over all MongoDB documents?
- How to use MongoDB $pull to delete documents within an Array?
- How to use MongoDB Aggregate to sort?
- How to calculate sum in MongoDB with aggregate()?
- MongoDB aggregate $slice to get the length of the array

Advertisements