这是我的数据格式:
"request" : {
"_id" : 1003,
"user" : {
"username" : "",
"password" : "",
"_id" : 1111,
"gender" : "male",
},
"request" : {
"merchantid" : "TA456",
"txnAmount" : 18000,
"fee" :0,
"IssuerID" : "18801111",
"bankID" : "888888",
}
},
"confirmation" : true
}`
我无法得到&request; request.request.txnAmount' group by" request.user._id'。
这是我的疑问:
db.getCollection('megabank_response').aggregate(
[ { $group : {
_id : "request.user._id",
totalPrice: { $sum: "request.request.txnAmount"},
count: { $sum: 1 }
}
}
])
得到结果:
{
"_id" : "request.user._id",
"total Price" : 0,
"count" : 4.0
}
任何人都可以帮助我,为什么我的查询无法计算总和?
答案 0 :(得分:1)
您似乎在组聚合函数中缺少$符号。
db.megabank_response.aggregate([{
$group: {
_id: "request.user._id",
ss: {
$sum: "request.request.txnAmount"
}
}
}]);
给出:{ "_id" : "request.user._id", "ss" : 0 }
但正确的答案是:
db.megabank_response.aggregate([{
$group: {
_id: "$request.user._id",
ss: {
$sum: "$request.request.txnAmount"
}
}
}]);
答案 1 :(得分:0)
我设法使用this source的答案找出了查询。 但是,我的查询有点太乱了。有什么方法可以优化它吗?
db.getCollection('megabank_response').aggregate([
{
"$match": {
"request.user._id": 1111
}
},
{
"$group":{
_id : "request.user._id",
totalPrice: { $sum: '$request.request.txnAmount'},
count: { $sum: 1 }
}
}
])
结果:
{
"_id" : "request.user._id",
"totalPrice" : 62000,
"count" : 3.0
}
答案 2 :(得分:0)
尝试:
db.getCollection('megabank_response').aggregate([{
$group: {
_id : "request.user._id",
totalPrice: { $sum: "$request.request.txnAmount"},
count: { $sum: 1 }
}
}])