Return All documents from collection but add a key to those satisfying the query Return All documents from collection but add a key to those satisfying the query mongoose mongoose

Return All documents from collection but add a key to those satisfying the query


Please use this in one line:

db.users.aggregate([{$set:{"isMatchingQuery":{$eq:["$Gender","Male"]}}}])

checkout the playground


Something like this is possible with the aggregation framework.

It would look like this:

db.users.aggregate([  {    $set: { "isMatchingQuery": { $eq: [ "$Gender", "Male" ] } }  }])


Thank you everyone for helping out. Interestingly while digging more I found another way this can be done. Kind of a hack.

db.users    .aggregate([      {        $project: {          _id: 1,          isMatchingQuery: {$eq: ["$Gender", "Male"] },          name: 1,        },      },    ])

Does the work for both $set and $project at once, for someone if they want only specific keys in the response.