如何在 MongoDB 中計算並求和兩個日期之間的欄位?


使用聚合 $gte 和 $lte 及 $sum 在兩個日期之間統計並求和一個欄位。我們先建立一個包含文件的集合——

> 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")
}

以下是使用 find() 方法顯示集合中所有文件的查詢——

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

這將產生以下輸出——

{
   "_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")
}

以下是計算並求和兩個日期之間的欄位的查詢——

> 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
...    }
... }
... }]
... );

這將產生以下輸出——

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

更新於: 27-3-2020

1K+ 瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.