Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Mongodb match a field only if specific value exists

I am making a dating app, where use have gender filter options (male, female, any). When user selects any I dont want to filter any gender field. I only want to filter/match gender field when user selects male or female options.

const matching_users = await User
  .aggregate([{
    $match: {
      $and: [{
          uid: {
            $in: matches
          }
        },
        {
          account_setuped: true
        },
        {
          $or: [{
            gender: settings.gender_filter === "any" ? "male" : settings.gender_filter
          }, {
            gender: settings.gender_filter === "any" ? "female" : settings.gender_filter
          }]
        }
      ]
    }
  }, ])

is there any better options other than this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

For the gender comparison part, I think can be simplified as:

.aggregate([{
  $match: {
    $and: [
      { 
        // Filter 1  
      },
      { 
        // Filter 2 
      },
      {
          $expr: {
            $or: [
              {
                $eq: [
                  "any",
                  settings.gender_filter
                ]
              },
              {
                $eq: [
                  "$gender",
                  settings.gender_filter
                ]
              }
            ]
          }
        }
      }
    ]
  }
}]

Sample Mongo Playground


Another approach with switch

{
  "$switch": {
    "branches": [
      {
        "case": {
          $eq: [
            "any",
            settings.gender_filter                  
          ]
        },
        "then": true
      },
    ],
    default: {
      $eq: [
        "$gender",
        settings.gender_filter           
      ]
    }
  }
}

Sample Mongo Playground ($switch)

Note: To test the demo, replace the value which contains the comment:

// settings.gender_filter

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!