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

219
Views
MongoDB match if input exists (aggregation)
$match: {
  date: { $gte: fromDate, $lte: toDate },
  if (userId) { 
    user: userId 
  }
},

I am trying to match a user only if there is a userId submitted. What is the best way to do this.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use mongoose query builder, to manage aggregations stages as per your conditions,

// INITIALIZE
let p = YourSchemaModel.aggregate();
// DATE FILTER
p.match({ date: { $gte: fromDate, $lte: toDate } });
// USER ID FILTER
if (userId) p.match({ user: userId });
// RESULT
let result = await p.exec();

Aggregation will auto merge $match stages if both are together!


Second option:

let result = await YourSchemaModel.aggregate().match(
  Object.assign(
    { date: { $gte: fromDate, $lte: toDate } }, 
    userId ? { user: userId } : {}
  )
).exec();
over 4 years ago · Santiago Trujillo 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!