How to get query output as nested document using aggregation stages

It is a single aggregation pipeline with a single access to the database but I use variable to express each stage since it is usually easier to understand. What make you think you call aggregate 4 times? My structured code is equivalent to the monolithic

db.getCollection( "user" ).aggregate( [
    { $match : { "request_id" : "02e97006-9d0d-41cc-84f6-185dbacafdd5" } } ,
    { $lookup : {
        from : "docs" ,
        localField : "_id" ,
        foreignField : "user_id" ,
        as : "doc" ,
        pipeline : [
            { $lookup : {
                from : "pages" ,
                localField : "_id" ,
                foreignField : "doc_id" ,
                as : "pages" ,
                pipeline : [
                    { $lookup : {
                        from : "paragraphs" ,
                        localField : "_id" ,
                        foreignField : "page_id" ,
                        as : "paragraph"
                    } }
                ]
            } }
         ]
    } }
] ) 
1 Like