如何使用接口{}动态查询mongodb



我试图使用 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 $or逻辑,如下面的代码

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

但即使将类型转换为 args,其他输入也不起作用 知道在这种情况下如何使用 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]}

最新更新