我是MongoDB的新手。我不了解太多的问题。我找不到的一个查询。"获取所有学生列表和地址清单的计数"。
文档:
{ _id: 123, students:
[
{
studentId:987,
studentName:"####",
addressList:[
{
addressId:678,
addressName:"XXXXXXXX"
},
{
addressId:679,
addressName:"XXXXXXX"
}
]
},
{
studentId:988,
studentName:"####",
addressList:[
{
addressId:680,
addressName:"XXXXX"
}
]
}
]
}
响应:
{
students:[
{
studentId:987,
studentName:"#####",
addressCount:2,
},
{
studentId:988,
studentName:"#####",
addressCount:1
}
]
}
您可以使用聚合
db.students.aggregate([
{
$unwind: "$students"
},
{
$group: {
_id: "$_id",
students: {
$push: {
addressCount: {
$size: "$students.addressList"
},
studentId: "$students.studentId",
studentName: "$students.studentName"
}
}
}
}
])