如何使用 golang 根据用户标准对 mongodb 集合应用多个过滤器

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

在我的前端,用户可以根据日期范围和/或目的应用过滤器。我如何生成 MongoDB 过滤器,以便如果用户在日期范围内传递,它仅将其用作过滤器?如果它只是目的,它只使用目的,如果它是两个,它应用两个过滤器。我正在使用戈朗。这是我的代码

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)

对过滤器使用单个映射(例如 bson.M),并且只为用户提供的过滤条件添加元素。

例如:

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)