mongodb aggregation lookup code example

Example 1: mongodb aggregate lookup array of objects

db.getCollection('widgets').aggregate([
    { $unwind: '$info' },
    {
        $lookup: {
            from: 'icons',
            localField: 'info.iconId',
            foreignField: '_id',
            as: 'info.icon'
        }
    },
    { $unwind: '$info.icon' },
    {
        $group: {
            _id: '$_id',
            root: { $mergeObjects: '$$ROOT' },
            info: { $push: '$info' }
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: ['$root', '$$ROOT']
            }
        }
    },
    {
        $project: {
            root: 0
        }
    }
]);

Example 2: lookup in mongodb array

> db.demo396.aggregate([
...    { "$lookup": {
...       "from": "demo395",
...       "let": { "details": "$details" },
...       "pipeline": [
...          { "$match": { "$expr": { "$in": [ "$_id", "$$details" ] } } }
...       ],
...       "as": "output"
...    }}
... ])