MongoDb按数组中的值查找

时间:2017-05-05 13:19:37

标签: mongodb mongoose

这是我的收藏品的模型:

classes:[{
            class:String,
            info:{
                    subjects:[String],
                    students:[{
                        name:String,
                        surname:String,
                        matriculae:Number,
                        path_1:String,
                        path_2:String
                    }],
                    classTeacher:{
                        name:String,
                        surname:String
                    }                   
                }
            }],
    accademicYear:String}];  

我想重温价值' matriculae'鉴于学生的姓名,姓氏和accademicYear。我不能把头包起来围绕它!感谢帮助。

1 个答案:

答案 0 :(得分:0)

如果您的意思是想要结果平面格式,请尝试以下方法:

 School.aggregate([
    {
        $unwind: '$classes'
    }, {
        $project: {
            accademicYear: 1,
            students: "$classes.info.students"
        }
    }, {
        $unwind: "$students"
    }, {
        $project: {
            accademicYear: 1,
            matriculae: "$students.matriculae",
            name: "$students.name",
            surname: "$students.surname",
        }
    }
    ])

如果类是集合,并且accademicYear在类集合中.Plus添加了匹配条件。

db.getCollection('classes').aggregate([{
    $project: {
        accademicYear: 1,
        students: "$info.students"
    }
}, {
    $unwind: "$students"
}, {
    $project: {
        accademicYear: 1,
        matriculae: "$students.matriculae",
        name: "$students.name",
        surname: "$students.surname",
    }
}, {
    $match: {
        name: name,
        surname: surname,
        accademicYear: year

    }

}])