willmahon
willmahon

Reputation: 339

How to have optional filters in mongodb queries

I have the following document model...

{
    _id: 'jr3h4h51gkjfhqd',
    first_name: 'bob',
    last_name: 'jones',
    age: 33,
    email: '[email protected]',
    phone_number: '',
    job: 'accountant',
    title: 'mr'
}

Is there a way I can write a query so that the query will have a filter for a certain value if a filter is provided, otherwise there won't be a filter applied for that property.

If a filter isn't provided, then that filter is left out (essentially, if no filters are provided, then all documents will be returned), but if only one filter is provided, then the query should only filter the documents based on that one filter. Here is the query if 5 filters are provided.

User.find(
  {
    first_name: FIRST_NAME_FILTER,
    last_name: LAST_NAME_FILTER,
    email: EMAIL_FILTER,
    job: JOB_FILTER,
    title: TITLE_FILTER
  }
)

Upvotes: 1

Views: 1077

Answers (1)

Takis
Takis

Reputation: 8695

You can do this in 2 places

  1. In the driver
    You can use the driver programming language and generate the query.
    For example
  query={}
  if(first_name_filter) query.add("first_name",first_name_filter);
  if(last_name_filter) query.add("last_name",last_name_filter);
  ...

  User.find(query);
  
  1. In the database
    MongoDB offers $cond aggregate operators,and you can do the same using aggregation,but if you know that information before you send the query there is no reason to do it in the database

Upvotes: 2

Related Questions