简体   繁体   中英

MongoDb find by value in array

here is the model of my collection :

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}];  

I'd like to retrive value 'matriculae' given the name,surname and accademicYear of a student. I cant wrap my head 'round it tho! Thanks for help.

If you mean you want the result flat format, try this:

 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",
        }
    }
    ])

In case of the classes is collection and accademicYear is inside of the classes collection.Plus added the match criteria.

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

    }

}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM