账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    mongodb的关联查询$lookup
    34
    0
    • 现在有这样的数据结构,比如在集合 class 里有一条
        {
            _id:ObjectId(123456789...),
            number:10,
            students:[
                {
                    studentId:ObjectId(123456789...)/* 这个是student集合的id */
                },
                {
                    studentId:ObjectId(123456789...)/* 这个是student集合的id */
                },
                ...
            ],
            teacher:ObjectId(123456789...),
            
        }
    • student 集合的数据结构是
        {
            _id:ObjectId(123456789...);
            name:'zhangsan',
            age:20,
        }
    • 现在的需求是查询class的时候把student也取出来,这样就要关联查询,我用的是pipeline的$lookup,但是好像只能查询class下一级的属性,比如关联查询teacher
        db.class.aggregate([
           {
              $lookup:
                 {
                    from: "teacher",
                    localField: "teacher",
                    foreignField: "_id",
                    as: "teacher"
                }
           }
        ])
    • 但是student下的studentId,就无法实现,我试过
        db.class.aggregate([
           {
               $unwind:students,
           },
           {
              $lookup:
                 {
                    from: "student",
                    localField: "students.studentId",
                    foreignField: "_id",
                    as: "student",/* 这里可能不对,但是不影响把student取出来 */
                }
           }
        ])
    • 希望有大佬可以解惑!不能改数据结构
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 戴蒙秦 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部