Mongodb 在mongo中使用组时,如何获得嵌套数组大小的嵌套数组?
这是收藏品Mongodb 在mongo中使用组时,如何获得嵌套数组大小的嵌套数组?,mongodb,Mongodb,这是收藏品 { "_id":ObjectId("5cc7d8e88c33e065c56b0883"), "age":70, "child":[ { "id":"son1", "age":40, "grandSon":[ { "id":"grand1", "age":10
{
"_id":ObjectId("5cc7d8e88c33e065c56b0883"),
"age":70,
"child":[
{
"id":"son1",
"age":40,
"grandSon":[
{
"id":"grand1",
"age":10
"grandGrandSon" :[
{
"id":"grandGrand1",
"age":10
},
{
"id":"grandGrand2",
"age":13
}
]
},
{
"id":"grand2",
"age":13
"grandGrandSon" :[
{
"id":"grandGrand1",
"age":12
},
{
"id":"grandGrand2",
"age":14
}
]
}
]
},
{
"id":"son2",
"age":40,
"grandSon":[
{
"id":"grand1",
"age":10
"grandGrandSon" :[
{
"id":"grandGrand1",
"age":15
},
{
"id":"grandGrand2",
"age":16
}
]
},
{
"id":"grand2",
"age":14
"grandGrandSon" :[
{
"id":"grandGrand1",
"age":12
},
{
"id":"grandGrand2",
"age":13
}
]
}
}
]
}
]
我想要这样的结果
父母年龄、子女大小和孙子数、孙子数
{
"_id": ObjectId("5cc7d8e88c33e065c56b0883"),
"age": 70,
"childCount": 2,
"grandSonsCount": 4
"grandGrandSonsCount": 8, //important
"grandSonsAgeCount": 105 // not important
}
这是我的密码
{
$lookup:
{
from: "..."
localField: "...",
foreignField: "..",
as: "child"
},
},
{ $unwind: "$child" }
{ $group : {
_id : "$_id",
age: {$first:"$age"},
childCount: {$sum: 1},
grandSonsCount : {$sum : {$size : "$child.grandSon"}},
grandGrandSonsCount :
{$sum : {$sum : {$size : "$child.grandSon.grandGrandSon"}}},
//it is return 4(grandSonsCount)
}},
我使用查找,为上述集合(子集合)制作
我想修改
/{$sum:{$sum:{$size:$child.grands.grandSon}}}
它返回孙子数,但我想得到孙子数
如何在大小的嵌套数组中获取嵌套数组
我想要孙子的尺寸
我该怎么办呢???你需要
放松你的孩子数组和孙子数组才能得到你的孙子数组的大小
试试这个:
db.collection_name.aggregate[{
$addFields : {
childCount : {$size : "$child"}
}
},
{
$unwind : "$child"
},{
$unwind : "$child.grandSon"
},{
$group :{
_id : "$_id",
age : {$first : "$age"},
childCount : {$first : "$childCount"},
grandSonsCount : {$sum : 1},
grandGrandSonsCount : {$sum : {$size : "$child.grandSon.grandGrandSon"}},
grandSonsAgeCount : {$sum : "$child.grandSon.age"},
grandGrandSonAgeCount : {$sum : {$sum : "$child.grandSon.grandGrandSon.age"}}
}
}
]
只需添加childCount,这样我们就不会在展开两个数组后计算childCount时遇到任何问题
阅读更多关于和的信息。您需要放松您的孩子阵列和孙子阵列,才能获得您的孙子阵列的大小
试试这个:
db.collection_name.aggregate[{
$addFields : {
childCount : {$size : "$child"}
}
},
{
$unwind : "$child"
},{
$unwind : "$child.grandSon"
},{
$group :{
_id : "$_id",
age : {$first : "$age"},
childCount : {$first : "$childCount"},
grandSonsCount : {$sum : 1},
grandGrandSonsCount : {$sum : {$size : "$child.grandSon.grandGrandSon"}},
grandSonsAgeCount : {$sum : "$child.grandSon.age"},
grandGrandSonAgeCount : {$sum : {$sum : "$child.grandSon.grandGrandSon.age"}}
}
}
]
只需添加childCount,这样我们就不会在展开两个数组后计算childCount时遇到任何问题
阅读更多关于和的信息。您的孩子是数组还是对象?因为我觉得你的文件有错误。子对象表示为数组,但它没有用于对象的花括号。它应该是一个对象,或者是一个对象数组。一个数组不能有fieldswait我很抱歉ㅠㅠ您的孩子是数组还是对象?因为我觉得你的文件有错误。子对象表示为数组,但它没有用于对象的花括号。它应该是一个对象,或者是一个对象数组。一个数组不能有fieldswait我很抱歉ㅠㅠ很抱歉ㅠㅠ, 我把它改了ㅠㅠ, 我修改了它