Computer >> Computer tutorials >  >> Programming >> MongoDB

How to count and sum a field between 2 dates in MongoDB?


Use aggregation $gte and $lte along with $sum to count and sum a field between 2 dates. Let us first create a collection with documents −

> db.countandsumdemo.insertOne({"Value":10,"created_at":ISODate('2019-10-11')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038e6df5e889d7a51994fa")
}
> db.countandsumdemo.insertOne({"Value":50,"created_at":ISODate('2019-01-31')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038e77f5e889d7a51994fb")
}
> db.countandsumdemo.insertOne({"Value":100,"created_at":ISODate('2019-06-31')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038e8af5e889d7a51994fc")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.countandsumdemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e038e6df5e889d7a51994fa"),
   "Value" : 10,
   "created_at" : ISODate("2019-10-11T00:00:00Z")
}
{
   "_id" : ObjectId("5e038e77f5e889d7a51994fb"),
   "Value" : 50,
   "created_at" : ISODate("2019-01-31T00:00:00Z")
}
{
   "_id" : ObjectId("5e038e8af5e889d7a51994fc"),
   "Value" : 100,
   "created_at" : ISODate("2019-07-01T00:00:00Z")
}

Following is the query to count and sum a field between 2 dates −

> db.countandsumdemo.aggregate(
...    [{
...       $match: {
...          created_at: {
...             $gte: new Date('2019-05-01'),
...             $lte: new Date('2019-12-31')
...          }
...       }
...    }, {
... $group: {
...    _id: null,
...    SUM: {
...       $sum: "$Value"
...    },
...    COUNT: {
...       $sum: 1
...    }
... }
... }]
... );

This will produce the following output −

{ "_id" : null, "SUM" : 110, "COUNT" : 2 }