如何计算mongodb中sub-sub内部列表的大小?

时间:2019-03-11 04:12:00

标签: database mongodb nosql mongodb-query nosql-aggregation

我是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
             }
         ]
}

1 个答案:

答案 0 :(得分:0)

您可以使用aggregation

db.students.aggregate([
  {
    $unwind: "$students"
  },
  {
    $group: {
      _id: "$_id",
      students: {
        $push: {
          addressCount: {
            $size: "$students.addressList"
          },
          studentId: "$students.studentId",
          studentName: "$students.studentName"
        }
      }
    }
  }
])