登录
首页 >  Golang >  Go问答

如何使用interface{}动态查询mongodb

来源:stackoverflow

时间:2024-04-14 12:54:32 219浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何使用interface{}动态查询mongodb》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我正在尝试使用 go 接口进行动态 mongodb 查询,如下所示

func (m *nfinstancedataaccess) findip(preferrednfinstances string, args ...interface{}) ([]model.nfprofile, bool) {
    var ip []model.nfprofile
    pipeline := bson.m{"nftype": preferrednfinstances, "allowednssais.sst": args, "allowednssais.sd": args}
    filter := bson.m{"ipv4addresses": true}
    err := db.c(collection).find(pipeline).select(filter).all(&ip)
    if err != nil {
        return ip, false
    }
    return ip, true
}

当我在 http 服务器处理程序中使用该函数时,没有错误

nfinstanceip, success := da.findip(targetnftype, sst, sd)
            if !success {
                writeerror(response, errinternalserver)
                return
            }

但响应 nfinstanceip 始终为空,即使我的 mongodb 集合中存在与 findip 参数匹配的值。 当我使用其他类型(如下面的代码中的整数和字符串)时,一切正常。

func (m *nfinstancedataaccess) findip(preferrednfinstances string, sst int, sd string) ([]model.nfprofile, bool) {
    var ip []model.nfprofile
    pipeline := bson.m{"nftype": preferrednfinstances, "allowednssais.sst": sst, "allowednssais.sd": sd}
    filter := bson.m{"ipv4addresses": true}
    err := db.c(collection).find(pipeline).select(filter).all(&ip)
    if err != nil {
        return ip, false
    }
    return ip, true
}

谁能向我解释一下为什么使用接口不起作用以及如何动态编写这个函数?

按照建议修改函数以使用 mongodb $或如下代码的逻辑

func (m *nfinstancedataaccess) findip(preferrednfinstances string, args ...interface{}) ([]model.nfprofile, bool) {
    var ip []model.nfprofile
    pipeline := bson.m{
        "nftype": preferrednfinstances,
        "$or": []interface{}{
            bson.m{"snssais.sst": args[0].(int32), "snssais.sd": args[1].(string)},
            bson.m{"amfinfo.tailist.tac": args},
            bson.m{"smfinfo.tailist.tac": args},
            bson.m{"upfinfo.tailist.tac": args},
        },
    }
    filter := bson.m{"ipv4addresses": true}
    err := db.c(collection).find(pipeline).select(filter).all(&ip)
    if err != nil {
        return ip, false
    }
    return ip, true
}

逻辑 $or 不起作用。仅当我的 findip 输入匹配时才有效

bson.M{"sNssais.sst": args[0].(int32), "sNssais.sd": args[1].(string)}

但即使将类型转换设置为参数,其他输入也不起作用 知道在这种情况下如何使用 mongodb 逻辑 $or 吗?


解决方案


您需要执行索引,如果需要,还需要类型转换

pipeline := bson.m{"nftype": preferrednfinstances, "allowednssais.sst": args[0].(int), "allowednssais.sd": args[1].(string)}

或者

pipeline := bson.M{"nfType": preferredNfInstances, "allowedNssais.sst": args[0], "allowedNssais.sd": args[1]}

终于介绍完啦!小伙伴们,这篇关于《如何使用interface{}动态查询mongodb》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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