MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come applicare la condizione sul risultato di $lookup in mongoDB?

Non puoi usare "$match" con un metodo oggetto dopo "$lookup", perché il valore restituito di "$lookup" sono valori di matrice. È meglio aggiungere la funzione "$unwind" dopo la ricerca, quindi raggrupparla.

Esempio di query

 db
.album
.aggregate([
    {
        $lookup:{
            from:"photo",
            localField:"_id",
            foreignField:"album_id",
            as:"photo"
        }
     },
    {
        preserveNullAndEmptyArrays : true,
        path : "$photo"
    },
    {
        $match:{
            "photo.flag": 1
        }
     },
     {
        $group : {
            _id : {
                id : "$_id",
                album_name: "$album_name",
                album_description: "$album_description",
                emoji_id: "$emoji_id"
            },
            photo: {
                $push : "$photo"
            }
        }
     }
    {
         $lookup:{
            from:"emoji",
            localField:"_id.album_emoji",
            foreignField:"_id",
            as:"emoji"
         }
    },
    {
         $project:{
            album_name:"$album_name",
            album_description:"$album_description",
            emoji:"$emoji",
            photo:"$photo",
            total_photos: {$size: "$photo"}
         }
    }
])

Oppure usa "$filtro".

db
.album
.aggregate([
    {
        $lookup:{
            from:"photo",
            localField:"_id",
            foreignField:"album_id",
            as:"photo"
        }
     },
    {
        $project: {
            id : "$_id",
            album_name: "$album_name",
            album_description: "$album_description",
            emoji_id: "$emoji_id",
            photo: {
                $filter : {
                    input: "$photo",
                    as : "photo_field",
                    cond : {
                        $eq: ["$$photo_field.flag",1]
                    }
                }
            }
        }
    },
    {
         $lookup:{
            from:"emoji",
            localField:"album_emoji",
            foreignField:"_id",
            as:"emoji"
         }
    },
    {
         $project:{
            album_name:"$album_name",
            album_description:"$album_description",
            emoji:"$emoji",
            photo:"$photo",
            total_photos: {$size: "$photo"}
         }
    }
])