使用聚合框架和$match以及$group运算符来尝试一下,例如:
db.tickets.aggregate([
{ $match: { time: {$gte: a, $lte: tomorrow} } },
{ $group: { _id: null, amount: { $sum: "$amount" } } }
])
例如,使用此类测试数据。
{
"_id" : ObjectId("57e0ed40828913a99c2ceb46"),
"time" : 20,
"amount" : 40
}
{
"_id" : ObjectId("57e0ed40828913a99c2ceb47"),
"time" : 40,
"amount" : 20
}
{
"_id" : ObjectId("57e0ed40828913a99c2ceb48"),
"time" : 50,
"amount" : 10
}
{
"_id" : ObjectId("57e0ed40828913a99c2ceb49"),
"time" : 10,
"amount" : 5
}
一个(带有虚拟时间范围的)管道如下所示:
db.tickets.aggregate([
{ $match: { time: {$gte: 20, $lte: 40} } },
{ $group: { _id: null, amount: { $sum: "$amount" } } }
])
会给您一个如下的结果
{
"_id" : null,
"amount" : 60
}
![Pipeline in action](https://istack.dev59.com/dUTUL.gif)