MongoDB aggregate: $lookup by _id, then get first element value MongoDB aggregate: $lookup by _id, then get first element value mongodb mongodb

MongoDB aggregate: $lookup by _id, then get first element value


You can achieve that by appending a $project stage using the $arrayElemAt operator to your aggregation pipeline like this

// your previous stages incl. lookup...$project: {    fromUser: { $arrayElemAt: ["$fromUser.userName", 0] },    toUser: { $arrayElemAt: ["$toUser.userName", 0] }}...