1
MongoDB的組匯聚我有以下樣本採集:與條件
{
"_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
它。