登录
首页 >  Golang >  Go问答

在 Golang 中如何通过BSON来动态创建MongoDB的$match查询

来源:stackoverflow

时间:2024-02-23 17:06:25 265浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《在 Golang 中如何通过BSON来动态创建MongoDB的$match查询》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

当我尝试为 mongodb 编写 bson 时遇到了麻烦,尤其是当尝试创建动态 bson 时。这是我在 mongodb 中的查询。

db.fee_report.aggregate(
    [ 
        { $match : { client_id : 2 } },
        { $match : { trx_type : "close payment" } },
        { $match: { execution_date: {$gte: "2021-02-01", $lte: "2021-02-06"} } },
    ]
);

这是我的示例请求:

{
    "page": 1,
    "max_rows": 20,
    "order_by": "created_at",
    "order_type": "asc",
    "date_range": {
        "from": "2021-02-01",
        "to": "2021-02-02"
    },
    "search": [
        {
            "column": "client_id",
            "value": "2"
        }
    ]
}

请参阅日期范围和搜索字段,因为这些字段是动态的。

{ $match : { client_id : 2 } },
{ $match : { trx_type : "close payment" } },
{ $match: { execution_date: {$gte: "2021-02-01", $lte: "2021-02-06"} } },

例如,有时我们不发送 client_id,但它应该是

{ $match : { trx_type : "close payment" } },
{ $match: { execution_date: {$gte: "2021-02-01", $lte: "2021-02-06"} } },

这是我的 go 代码。我在尝试为此传递动态 bson 时遇到了麻烦。

func AggregateToMongo(d constant.DateRange, c ...constant.Search) bson.M {
    filter := bson.M{}

    if d != (constant.DateRange{}) {
        filter["execution_date"] = map[string]interface{}{
            "$gt": d.From,
            "$lt": d.To,
        }
    }

    for _, n := range c {
        if n.Params != "" {
            filter[n.ColumnName] = n.Params
        }
    }

    vr := bson.M{}

    for v, i := range filter {
        vr[v] = i
    }

    return bson.M{
        "$match": vr,
    }
}

之后我收到一个错误。请有人帮助我。如果有人能帮助我解决这个问题,我将不胜感激。我被这个问题困扰了8个多小时。 非常感谢。


解决方案


func AggregateToMongo(d constant.DateRange, c ...constant.Search) bson.M {
    dr := bson.M{}
    if d != (constant.DateRange{}) {
        dr = bson.M{"execution_date": bson.M{
            "$gte": d.From, "$lte": d.To},
        }
    }

    p := bson.M{}
    for _, n := range c {
        if n.Params != "" {
            if n.ColumnName == "client_id" {
                i, err := strconv.ParseInt(n.Params, 10, 32)
                if err != nil {
                    panic(err)
                }
                p = bson.M{n.ColumnName: i}
            } else {
                p = bson.M{n.ColumnName: n.Params}
            }
        }
    }

    filter := bson.M{
        "$match": bson.M{
            "$and": []bson.M{dr, p},
        },
    }

    return filter
}

以上就是《在 Golang 中如何通过BSON来动态创建MongoDB的$match查询》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>