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

1K
Views
How to apply multiple filters on mongodb collection based on user criteria using golang

From my frontend, users can apply filters based on date range or purpose, or both. How do i generate the MongoDB filter so that if users pass in date range, it only uses that as a filter? If it is only purpose, it only uses purpose and if it is both, it applies both filters. I am using golang. Here is my code

var filterData map[string]interface{}
if purpose != "" {
        filterData = bson.M{
            "purpose": purpose,
     }
var filterDate map[string]interface{}
if //condition for date range{
filterDate = bson.M{
        "paymentDate": bson.M{
            "$gte": startdate,
            "$lt":  enddate,
        },
}
}
//here i cant apply both
cursor, err = collection.Find(conn.DatabaseContext, findQuery)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use a single map for the filter (e.g. bson.M), and only add elements for filter conditions that the user supplied.

For example:

var purpose string
var startDate, endDate time.Time

filter := bson.M{}
if purpose != "" {
    filter["purpose"] = purpose
}
if !startDate.IsZero() && !endDate.IsZero() {
    filter["paymentDate"] = bson.M{
        "$gte": startDate,
        "$lt":  endDate,
    }
}

cursor, err = collection.Find(ctx, filter)
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!