我有以下示例集合:
{
"_id" : ObjectId("59007c230c16863f9ae8ea00"),
"user_id" : 1,
"transaction_time" : ISODate("2017-04-26T10:52:33.000Z"),
"type" : "data_plan",
"amount" : 540.0,
"updated_at" : ISODate("2017-04-26T10:53:23.389Z"),
"created_at" : ISODate("2017-04-26T10:53:23.389Z")
}
这相当于我想在 SQL 中执行的操作:
SELECT user_id, SUM(amount) as total_amount
FROM user_transactions
WHERE type = 'data_plan'
AND transaction_time BETWEEN '2017-04-14' AND '2017-04-20'
GROUP BY user_id
HAVING total_amount >= 2000
这是我当前执行相同操作的查询;
db.user_transactions.aggregate([{
'$group': {
'_id': {
'user_id': '$user_id'
},
'amount': {
'$sum': '$amount'
},
'user_id': {
'$first': '$user_id'
}
}
},
{
'$match': {
'amount': {
'$gte': 2000
}
'type': {
'$eq': 'data_plan'
},
'transaction_time': {
$gte: ISODate("2017-04-14T00:00:00.000Z"),
$lt: ISODate("2017-04-20T00:00:00.000Z")
}
}
}
])
它没有返回任何结果,但是当我从 $match
中删除 transaction_time
和 type
时,它返回了。
最佳答案
我想我明白了;
db.user_transactions.aggregate([{
$match: {
type: {
$eq: "data_plan"
},
transaction_time: {
$gte: ISODate("2017-04-14T00:00:00.000Z"),
$lt: ISODate("2017-04-20T00:00:00.000Z")
}
}
}, {
$group: {
_id: "$user_id",
amount: {
$sum: "$amount"
},
user_id: {
$first: "$user_id"
}
}
}, {
$match: {
amount: {
$gte: 2000
}
}
}])
您的查询的问题是,您试图在 $group
阶段结束时立即执行所有 $match
逻辑,但是字段 type
和 transaction_time
分组后不存在,因此我在分组前移动了它们,并且有效。在 Online MongoDB Shell 上测试.
如果你遇到聚合问题,因为它是一个操作数组,正在创建一个管道,最好单独测试每个操作,只检查 $group
操作结果就足够了解决您的问题。
关于带条件的 MongoDB 组聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43632551/