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

Viewed 46

I am a newbie to MongoDB.

I wanted to know if something like this can be achieved?

users Collection : 

    [
      {
        name : "John",
        Gender : "Male",
      },
      {
        name : "Alex",
        Gender : "Male",
      },
      {
        name : "Eva",
        Gender : "Female",
      }
    ]
    db.users.find({Gender : "Male"});

    Response :

    [
      {
        name : "John",
        Gender : "Male",
        isMatchingQuery : true,
      },
      {
        name : "Alex",
        Gender : "Male",
        isMatchingQuery : true,
      },
      {
        name : "Eva",
        Gender : "Female",
        isMatchingQuery : false,
      }
    ]

Can we get something like this where every document is return in response but the ones satisfying the query has a key added with value true and others not satisfying as false. Is it possible through aggregate?

3 Answers

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.

Related