Mongoose include fields from a secondary document using $lookup Mongoose include fields from a secondary document using $lookup mongoose mongoose

Mongoose include fields from a secondary document using $lookup


You need $lookup with custom pipeline to match against name or location field and then simply you can run $project to get desired format of your result documents:

db.Locations.aggregate([    {        $lookup: {            from: "Orders",            let: { loc_id: "$_id" },            pipeline: [                { $match: { $expr: { $eq: [ "$$loc_id", "$_id" ] } } },                { $project: { _id: 0, products: 1 } }            ],            as: "orders"        }    },    {        $match: { orders: { $ne: [] } }    },    {        $project: {            _id: 1,            name: 1,            products: "$orders.products"        }    }])

Mongo Playground