我在mongodb中有一组事务数据,如下所示:
[
{timestamp: ISODate("2015-11-10T11:33:41.075Z"), nominal: 25.121},
{timestamp: ISODate("2015-11-22T11:33:41.075Z"), nominal: 25.121},
{timestamp: ISODate("2015-11-23T11:33:41.075Z"), nominal: 26.121},
{timestamp: ISODate("2015-12-03T11:33:41.075Z"), nominal: 30.121},
]如何使用mongodb的aggregate计算每个月的总事务量?
我试过:
db.getCollection('transaction').aggregate([
{ $group: {_id: "$timestamp", total: {$sum: "$nominal"} } }
])但是它失败了,因为我使用timestamp而不是month。我不想在事务数据中添加另一个month字段。我想到了一个为$group管道定制的函数,它返回月份值。
发布于 2015-11-27 07:27:19
发布于 2021-12-05 09:31:47
如果您希望对每个year-month进行分组(以避免不同年份的月份分组在一起),则可以使用$dateToString
// { timestamp: ISODate("2015-11-10T11:33:41.075Z"), nominal: 25.121 }
// { timestamp: ISODate("2015-11-22T11:33:41.075Z"), nominal: 25.121 }
// { timestamp: ISODate("2015-11-23T11:33:41.075Z"), nominal: 26.121 }
// { timestamp: ISODate("2015-12-03T11:33:41.075Z"), nominal: 30.121 }
db.collection.aggregate([
{ $group: {
_id: { $dateToString: { date: "$timestamp", format: "%Y-%m" } },
total: { $sum: "$nominal" }
}}
])
// { _id: "2015-12", total: 30.121 }
// { _id: "2015-11", total: 76.363 }https://stackoverflow.com/questions/33952057
复制相似问题