Database
[/**Should return - Has Extras & Quotation*/{_id:1,Extras:[{Name:"Extra1 with Empty Quotation - Should not return",QuotationHistory:[]},{Name:"Extra1 with Quotations - Should return Quotation with last item",QuotationHistory:[{Date:"2023-01-01",Items:[{Name:"Item 1",Price:90}]},{Date:"2023-01-02",Items:[{Name:"Item 2",Price:10}]}]},{Name:"Extra1 with null Quotation - Should not return",QuotationHistory:null},{Name:"Extra1 with No Quotation - should not return",}]},{_id:2,Extras:[{Name:"Extra2 with Quotations - Should return Quotation with last item",QuotationHistory:[{Date:"2023-01-01",Items:[{Name:"Item 1",Price:90}]},{Date:"2023-01-02",Items:[{Name:"Item 2",Price:10}]}]},{Name:"Extra2 with Quotations - Should return Quotation with last item",QuotationHistory:[{Date:"2023-01-01",Items:[{Name:"Item 100",Price:100}]},{Date:"2023-01-02",Items:[{Name:"Item 200",Price:200}]}]}]},/**Should return - Has Extras & Quotation*/{_id:4,Extras:[{Name:"Should return - Has Extras & Quotation",QuotationHistory:[{Date:"2023-01-01",Items:[{Name:"Item 1",Price:90}]},{Date:"2023-01-02",Items:[{Name:"Item 2",Price:10}]}]}]},/**Should not return - Empty Quotation*/{_id:5,Extras:[{QuotationHistory:[]}]},/**Should not return - Empty Extras*/{_id:6,Extras:[]}]
Query
db.collection.aggregate([{$set:{Extras:{"$filter":{"input":"$Extras","as":"ex","cond":{$gt:[{$size:{$ifNull:["$$ex.QuotationHistory",[]]}},0]}}}}},{$match:{$expr:{$gt:[{$size:{$ifNull:["$Extras",[]]}},0]}}},{$set:{Extras:{"$map":{"input":"$Extras","as":"ex","in":{"$mergeObjects":["$$ex",{QuotationHistory:{$last:"$$ex.QuotationHistory"}}]}}}}}])