如何在 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 }
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP