【发布时间】:2014-09-03 09:18:19
【问题描述】:
我是 mongo 的新手,我正在尝试从名为“transactions”的 mongo db 集合中获取总金额的总和,其中“paid”为真,“creationDate”为 2014 年 9 月,按天分组.
在 Postgres 中,我可以这样写:
select to_char("creationDate", 'YYYY-MM') as "Month", sum(totalamount)
from transactions
where "creationDate" >= '2014-09-01'
and paid is true
group by "Month"
但是,我不确定如何在 Mongo 中添加creationDate 和paid 的条件。我阅读了条件聚合,但我不确定如何让它在日期的日期和月份以及逻辑条件下工作。
样本数据:
{ "totalamount" : 10, "creationDate" : ISODate("2014-09-01T01:00:58.909Z"), "paid" : true}
{ "totalamount" : 30, "creationDate" : ISODate("2014-09-01T03:00:58.909Z"), "paid" : true}
{ "totalamount" : 20, "creationDate" : ISODate("2014-09-02T01:00:58.909Z"), "paid" : true}
这是我尝试过的:
db.transactions.aggregate(
[
{
$group:
{
_id: {
day: { $dayOfMonth: "$creationDate"},
month:
{
$cond: [{ $gte: [$month: "$creationDate", 9]},9,0]
},
year:
{
$cond: [{ $gte: [$year: "$creationDate", 2014]},2014,0]
},
},
collected: {
$sum: {
$cond: [
{"$paid":"true"}, "$totalamount",0]
}
}
}
}
]
)
但是,我收到了"SyntaxError: Unexpected token :"
对此的任何见解都会非常有帮助。谢谢!
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework