Select fields Conditionally in MongoDB

Viewed 32

I want to select from mongoose for example the fields mobileNumber and email if the user type in the same schema is admin and don't select them if the user type is 'individual'. All these fields are in the same schema. So, how can I select conditionally in mongoDB ?

Here is my Implementation:

const userData = await userProvider.findOne(
  { _id: userId },
  'mobileNumber email'
);

where findOne is a function that takes 1st argument as filter and second argument as select fields

1 Answers

I don't know if there is another simpler way but you can use $cond in a project stage to keep the value if is admin or else $$REMOVE like this:

db.collection.find(
{ _id: userId },
{
  "_id": 0,
  "type": 1,
  "email": {
    "$cond": [
      {
        "$eq": [
          "$type",
          "admin"
        ]
      },
      "$email",
      "$$REMOVE"
    ]
  },
  "mobileNumber": {
    "$cond": [
      {
        "$eq": [
          "$type",
          "admin"
        ]
      },
      "$mobileNumber",
      "$$REMOVE"
    ]
  }
})

Example here

Related