我是MongoDB的新手。我对MongoDB查询不多。我找不到一个查询。 “获取所有学生的列表和addressList的计数”。
文档:
{ _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
}
]
}
答案 0 :(得分:0)
您可以使用aggregation
db.students.aggregate([
{
$unwind: "$students"
},
{
$group: {
_id: "$_id",
students: {
$push: {
addressCount: {
$size: "$students.addressList"
},
studentId: "$students.studentId",
studentName: "$students.studentName"
}
}
}
}
])