我有一个mongoDB,其中包含这样的条目:
{
"_id" : ObjectId("5cf3e2e0839abf5afbf05052"),
"sex" : "Male",
"location" : {
"city" : "Solingen",
"address" : {
"streetname" : "Dawn",
"streetnumber" : "888"
}
},
"credit" : [
{
"type" : "switch",
"number" : "201864776633337",
"currency" : "CNY",
"balance" : "4898.89"
},
{
"type" : "jcb",
"number" : "3552382704063930",
"currency" : "IDR",
"balance" : "4501.62"
}
]
},
{
"_id" : ObjectId("5cf3e2e0839abf5afbf051c6"),
"sex" : "Male",
"location" : {
"city" : "Hamburg",
"address" : {
"streetname" : "Brentwood",
"streetnumber" : "6"
}
},
"nationality" : "Germany",
"credit" : [
{
"type" : "jcb",
"number" : "4017959913393",
"currency" : "SEK",
"balance" : "3867.38"
},
{
"type" : "jcb",
"number" : "5100136044479699",
"currency" : "CNY",
"balance" : "4323.61"
}
]
},
我想使用合计卡中的平均金额和总金额来执行。
所以我的代码应该映射卡片阵列并增加卡片上的余额。
我尝试使用map和mergeObjects
[
{ "$addFields": {
"credit": {
"$map": {
"input": "$credit",
"in": {
"$mergeObjects": [
"$$this",
{
"convertedBalance": {
"$toDouble": "$$this.balance"
}
}
]
}
}
}
}},
{ $unwind : "$credit" },
{ $match : { sex : "Female", nationality : "Poland"}},
{$group : { _id : "$credit.currency", avgBalance : {$avg : "$convertedBalance"}, sumBalance : {$sum : "$convertedBalance"}}}
]
).toArray());
但是对于null
,结果是avgBalance
;对于sumBalance
,结果是0,如下所示:
connecting to: mongodb://localhost:27017/nbd?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b49b33ce-808b-4814-a31e-7a70ce6fe0d7") }
MongoDB server version: 4.0.10
[
{
"_id" : "MYR",
"avgBalance" : null,
"sumBalance" : 0
},
{
"_id" : "ALL",
"avgBalance" : null,
"sumBalance" : 0
},
,输出应该类似于:
"_id" : "AFN",
"avgBalance" : 5585.163333333333,
"sumBalance" : 16755.489999999998
},
答案 0 :(得分:1)
当您引用不存在的根级别字段时,运行$group
阶段convertedBalance
嵌套在credit
中,请尝试:
{
$group : {
_id : "$credit.currency",
avgBalance : {$avg : "$credit.convertedBalance"},
sumBalance : {$sum : "$credit.convertedBalance"}
}
}