2

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)
icza
  • 389,944
  • 63
  • 907
  • 827
Mcbaloo
  • 157
  • 5
  • 18

1 Answers1

3

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)
icza
  • 389,944
  • 63
  • 907
  • 827