MongoDB aggregate to get the Mean daily average count of recorded documents in a collection?

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 11-May-2020 09:04:42
Advertisements