Search code examples
mongodbgomongo-go

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)

Solution

  • 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)