mongodb aggregation with $project to conditionally exclude a field
Starting in mongoDB 3.6, you can use the REMOVE variable to exclude fields conditionally.
In your particular case, the project stage should look like this:
aggregate.project({
_id: 1,
last: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$date', '$$REMOVE' ] },
user: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$user', '$$REMOVE' ] },
app: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$app', '$$REMOVE' ] }
});
I think it's not possible yet.
Error message from the shell when trying to exclude a non-_id field :
The top-level _id field is the only field currently supported for exclusion