sql >> Base de Datos >  >> NoSQL >> MongoDB

$búsqueda cuando ForeignField está en una matriz anidada

No estoy seguro de entender tu pregunta por completo, pero esto debería ayudarte:

db.student.aggregate([{
    $match: { _id: ObjectId("657...") }
}, {
    $lookup: {
        from: 'library',
        localField: '_id' ,
        foreignField: 'issued_to.student',
        as: 'result'
    }
}])

Si solo desea obtener todos los book_name s para cada estudiante puede hacer esto:

db.student.aggregate([{
    $match: { _id: ObjectId("657657657657657657657657") }
}, {
    $lookup: {
        from: 'library',
        let: { 'stu_id': '$_id' },
        pipeline: [{
            $unwind: '$issued_to' // $expr cannot digest arrays so we need to unwind which hurts performance...
        }, {
            $match: { $expr: { $eq: [ '$issued_to.student', '$$stu_id' ] } }
        }, {
            $project: { _id: 0, "book_name": 1 } // only include the book_name field
        }],
        as: 'result'
    }
}])