Sử dụng aggregation $match với $gte/$lte và $group với $sum. Tạo collection:
> 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") }
Hiển thị tài liệu (lưu ý: 31/6 tự động thành 1/7):
> db.countandsumdemo.find().pretty();
Aggregation đếm và tổng Value từ 1/5/2019 đến 31/12/2019:
> 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 } }} ]);Kết quả - 2 tài liệu (10/10 và 1/7), tổng = 110:
Giải thích:
$matchlọc theo khoảng ngày (sử dụng index nếu có).$groupvới_id: nullgom tất cả thành một nhóm.$sum: "$Value"tính tổng,$sum: 1đếm số lượng.