cha*_*hap 8 arrays mongodb mongodb-query aggregation-framework
{
"ArticleName": "Example Article",
"Comments": [
{
"Text": "Great Article",
"Responses": [
{
"Text": "No it isnt",
"Responses": [
{
"Text": "Yes it is"
}
]
},
{
"Text": "Spot on"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
每次出现的关键"文本"都会被视为注释(因此有4条评论).在Mongo中,最好的方法是什么?
您可以尝试下面的聚合
基本上,您必须使用循环遍历每个数组,并对不等于的$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 ] }
}
}}
]
}
}
}}
]
}
}
}
}
}}
])
Run Code Online (Sandbox Code Playgroud)
[
{
"commentsCount": 4
}
]
Run Code Online (Sandbox Code Playgroud)