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
Aggregation: group date in nested documents (nested object) and display the count?
For aggregation, use aggregate() in MongoDB. Group the dates with $group. Let us create a collection with documents −
> db.demo717.insertOne(
... {
... "shippingdetails":
... [
... {
... duedate:"2020-04-29 22:33:04",
... },
... {
... duedate:"2020-03-29 22:33:04",
... },
... {
... duedate:"2020-04-29 22:33:04",
... },
... {
... duedate:"2020-01-29 22:33:04",
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea9b3cd85324c2c98cc4c30")
}
Display all documents from a collection with the help of find() method −
> db.demo717.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ea9b3cd85324c2c98cc4c30"),
"shippingdetails" : [
{
"duedate" : "2020-04-29 22:33:04"
},
{
"duedate" : "2020-03-29 22:33:04"
},
{
"duedate" : "2020-04-29 22:33:04"
},
{
"duedate" : "2020-01-29 22:33:04"
}
]
}
Following is the query for aggregation to group date in nested documents (nested object) −
> db.demo717.aggregate(
... {
... $unwind:"$shippingdetails"},
... {
... $group: {
... _id: "$shippingdetails.duedate",
... count: {
... $sum: 1
... }
... }
... }
... )
This will produce the following output −
{ "_id" : "2020-01-29 22:33:04", "count" : 1 }
{ "_id" : "2020-03-29 22:33:04", "count" : 1 }
{ "_id" : "2020-04-29 22:33:04", "count" : 2 }Advertisements