{
"ArticleName": "Example Article",
"Comments": [
{
"Text": "Great Article",
"Responses": [
{
"Text": "No it isnt",
"Responses": [
{
"Text": "Yes it is"
}
]
},
{
"Text": "Spot on"
}
]
}
]
}
每次出现键“文本”都将被视为注释(因此有4条注释)。在Mongo上获得这种计数的最佳方法是什么?
答案 0 :(得分:1)
您可以尝试以下汇总
基本上,您必须使用$map
遍历每个数组,并计算Text
不等于$ne
undefined
db.collection.aggregate([
{ "$project": {
"commentsCount": {
"$sum": {
"$map": {
"input": "$Comments",
"as": "cc",
"in": {
"$add": [
{ "$cond": [{ "$ne": [ "$$cc.Text", undefined ] }, 1, 0 ] },
{ "$sum": {
"$map": {
"input": "$$cc.Responses",
"as": "dd",
"in": {
"$add": [
{ "$cond": [{ "$ne": [ "$$dd.Text", undefined ] }, 1, 0 ] },
{ "$sum": {
"$map": {
"input": "$$dd.Responses",
"as": "ee",
"in": { "$cond": [{ "$ne": [ "$$ee.Text", undefined ] }, 1, 0 ] }
}
}}
]
}
}
}}
]
}
}
}
}
}}
])
[
{
"commentsCount": 4
}
]