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

Fetch data between two dates and with a specific value in MongoDB. Group and get the sum with count?


To match, use $match in MongoDB and to get data between two dates, use $gte and $lte. Let us create a collection with documents −

> db.demo560.insertOne({"value1":40,"value2":40,shippingDate:new ISODate("2020-02-26")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e867")
}
> db.demo560.insertOne({"value1":20,"value2":60,shippingDate:new ISODate("2020-02-26")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e868")
}
> db.demo560.insertOne({"value1":40,"value2":70,shippingDate:new ISODate("2020-03-31")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e869")
}
> db.demo560.insertOne({"value1":40,"value2":130,shippingDate:new ISODate("2020-03-31")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e86a")
}

Display all documents from a collection with the help of find() method −

> db.demo560.find();

This will produce the following output −

{ "_id" : ObjectId("5e8f3d5254b4472ed3e8e867"), "value1" : 40, "value2" : 40, "shippingDate" : ISODate("2020-02-26T00:00:00Z") }
{ "_id" : ObjectId("5e8f3d5254b4472ed3e8e868"), "value1" : 20, "value2" : 60, "shippingDate" : ISODate("2020-02-26T00:00:00Z") }
{ "_id" : ObjectId("5e8f3d5254b4472ed3e8e869"), "value1" : 40, "value2" : 70, "shippingDate" : ISODate("2020-03-31T00:00:00Z") }
{ "_id" : ObjectId("5e8f3d5254b4472ed3e8e86a"), "value1" : 40, "value2" : 130, "shippingDate" : ISODate("2020-03-31T00:00:00Z") }

Following is the query to fetch data between two dates and with a specific value. Here, value1 40 is our specific value −

> db.demo560.aggregate([
... {
...    $match: {
...       "value1": 40,
...       "shippingDate": {
...          "$gte": ISODate("2020-02-26"),
...          "$lte": ISODate("2020-03-31")
...       }
...    }
... },
... {
...    $group: {
...       "_id": "$shippingDate",
...       total: {
...          $sum: '$value2'
...       },
...       count: {
...          $sum: 1
...       }
...    }
... }
... ])

This will produce the following output −

{ "_id" : ISODate("2020-03-31T00:00:00Z"), "total" : 200, "count" : 2 }
{ "_id" : ISODate("2020-02-26T00:00:00Z"), "total" : 40, "count" : 1 }