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

nidificato $ addFields in MongoDB

Dato che stai usando $unwind puoi farlo facilmente aggiungendo $match poiché espressione:"inquiries.routeHistory.status": "ended" restituirà true se ce n'è qualsiasi documento in routeHistory avente tale stato:

db.collection.aggregate([
    {
        $unwind: "$inquiries"
    },
    {
        $match: {
            "inquiries.routeHistory.status": "ended"
        }
    },
    {
        $addFields: {
            "inquiries.routeHistory": {
                $filter: {
                    input: "$inquiries.routeHistory",
                    cond: {
                        $eq: [ { $max: "$inquiries.routeHistory.routeDate" }, "$$this.routeDate" ]
                    }
                }
            }
        }
    },
    {
        $group: {
            _id: "$_id",
            callId: { $first: "$callId" },
            caller: { $first: "$caller" },
            inquiries: { $push: "$inquiries" }
        }
    }
])

Mongo Playground