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
MongoDB aggregate to get the Mean daily average count of recorded documents in a collection?
To get the mean daily average count of recorded documents, use aggregate(). Within that, use $project and $group.
Let us create a collection with documents −
Example
> db.demo451.insertOne({
... DueDate:new ISODate("2020-03-15T10:50:35.000Z"),
... Value: 10
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b5c5d71f552a0ebb0a6e9")
}
> db.demo451.insertOne({
... DueDate:new ISODate("2020-03-14T10:50:35.000Z"),
... Value: 10
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b5c5d71f552a0ebb0a6ea")
}
> db.demo451.insertOne({
... DueDate:new ISODate("2020-03-13T10:50:35.000Z"),
... Value: 10
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b5c5d71f552a0ebb0a6eb")
}
Display all documents from a collection with the help of find() method −
> db.demo451.find();
This will produce the following output −
{ "_id" : ObjectId("5e7b5c5d71f552a0ebb0a6e9"), "DueDate" : ISODate("2020-03-
15T10:50:35Z"), "Value" : 10 }
{ "_id" : ObjectId("5e7b5c5d71f552a0ebb0a6ea"), "DueDate" : ISODate("2020-03-
14T10:50:35Z"), "Value" : 10 }
{ "_id" : ObjectId("5e7b5c5d71f552a0ebb0a6eb"), "DueDate" : ISODate("2020-03-
13T10:50:35Z"), "Value" : 10 }
Following is the query to get the mean daily average count of recorded documents in a collection −
> db.demo451.aggregate({
... $match: {
... DueDate: {
... $lt: new ISODate()
... }
... }
... }, {
... $group: {
... _id: null,
... olderDate: {
... $min: "$DueDate"
... },
... sumValue: {
... $sum: "$Value"
... }
... }
... }, {
... $project: {
... _id: 0,
... averageValue: {
... $divide: ["$sumValue", {
... $divide: [{
... $subtract: [new ISODate(), "$olderDate"]
... }, 1000 * 60 * 60 * 24]
... }]
... }
... }
... })
This will produce the following output −
{ "averageValue" : 2.475558456547562 }Advertisements