- 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
GroupBy Date in MongoDB to count duplicate date records
To count duplicate date records in MongoDB, use aggregate() and $group. Let us create a collection with documents −
> db.demo160.insertOne({"DueDate":new ISODate()}); { "acknowledged" : true, "insertedId" : ObjectId("5e357525fdf09dd6d0853a04") } > db.demo160.insertOne({"DueDate":new ISODate("2019-01-11")}); { "acknowledged" : true, "insertedId" : ObjectId("5e357532fdf09dd6d0853a05") } > db.demo160.insertOne({"DueDate":new ISODate()}); { "acknowledged" : true, "insertedId" : ObjectId("5e357534fdf09dd6d0853a06") } > db.demo160.insertOne({"DueDate":new ISODate("2019-01-11")}); { "acknowledged" : true, "insertedId" : ObjectId("5e357538fdf09dd6d0853a07") } > db.demo160.insertOne({"DueDate":new ISODate("2020-04-10")}); { "acknowledged" : true, "insertedId" : ObjectId("5e357542fdf09dd6d0853a08") }
Display all documents from a collection with the help of find() method −
> db.demo160.find();
This will produce the following output −
{ "_id" : ObjectId("5e357525fdf09dd6d0853a04"), "DueDate" : ISODate("2020-02-01T12:55:01.983Z") } { "_id" : ObjectId("5e357532fdf09dd6d0853a05"), "DueDate" : ISODate("2019-01-11T00:00:00Z") } { "_id" : ObjectId("5e357534fdf09dd6d0853a06"), "DueDate" : ISODate("2020-02-01T12:55:16.787Z") } { "_id" : ObjectId("5e357538fdf09dd6d0853a07"), "DueDate" : ISODate("2019-01-11T00:00:00Z") } { "_id" : ObjectId("5e357542fdf09dd6d0853a08"), "DueDate" : ISODate("2020-04-10T00:00:00Z") }
Following is the query to group by date in MongoDB −
> db.demo160.aggregate([ ... { $group: { ... _id: { ... $add: [ ... { $dayOfYear: "$DueDate"}, ... { $multiply: ... [400, {$year: "$DueDate"}] ... } ... ]}, ... Frequency: { $sum: 1 }, ... d: {$min: "$DueDate"} ... } ... }, ... { $sort: {_id: 1} }, ... { $limit: 100}, ... { $project: { date: "$d", Frequency: 1, _id: 0} } ... ]);
This will produce the following output −
{ "Frequency" : 2, "date" : ISODate("2019-01-11T00:00:00Z") } { "Frequency" : 2, "date" : ISODate("2020-02-01T12:55:01.983Z") } { "Frequency" : 1, "date" : ISODate("2020-04-10T00:00:00Z") }
Advertisements