Mongodb $addFields does not outputs the data if null

Viewed 1184

i am struggling with an annoying problem. I am using aggregation in a query and i need to join some collections and the output has to be an object. This is my code...

usersModel.aggregate([
    {
        $match: { _id: ObjectId(req.params.id) }
    },
    {
        $lookup: {
            from: "agents",
            as: "agent",
            let: { "idAgent": "$agent" }, //$agent can be null
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $eq: ['$_id', "$$idAgent"] 
                        },
                    }
                }
            ],
        }
    },
    { $unwind: { path: '$agent', preserveNullAndEmptyArrays: true } },
    {
        $addFields: {
            agent: "$agent", //If $agent is null, it does not output the field agent...
        }
    }

])

If in the last Stage, the field $agent is null, $addFields does not output the field. There is any other approach to do it? i need just agent field as an object after lookup. Thanks

1 Answers

Add an $ifNull condition with $addFields

{
  "$addFields": {
    "agent": { "$ifNull": ["$agent", {}] }
  }
}
Related