Search code examples
mongodbmongoose-schemamongo-shell

Want to display all documents if a variable is passed blank or null in mongoDB


Following is my data in People Collection

{
  name : 'John Doe',
  gender : 'male'
},
{
  name : 'Emma',
   gender : 'female'
}
{
  name : 'Mr. Smith',
  gender : 'male'
}

If I run a query as below with

`variable = male`

`people.aggregate.([
 {
   $match : {
      gender : variable
  }
 }
])`

then all the documents with variable = male will be displayed, the same goes for female.

But if a condition comes like I have to display both genders , Male and Female and I also don't want to write another query and variable passes blank or null value then how should i display all documents with male and female in that scenario.

I am using moongoose library in backend. And for some reason I dont want to use .find()


Solution

  • The object passed to the $match stage or find method can be constructed ahead of time, which you can build conditionally based on variable content

    var query = {};
    if (variable) {
      query.gender=variable
    }
    people.aggregate.([
     {
       $match : query
     }
    ])