如何从MongoDb查询中编写go bson.M [英] How to write go bson.M from MongoDb query

查看:110
本文介绍了如何从MongoDb查询中编写go bson.M的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mongodb作为数据库.我可以使用命令从命令行查询数据库

I am using mongodb as database. I'm able to query the database from the command line using the command

db.nfinstances.distinct("ipv4Addresses",{"nfType":"AMF", "amfInfo.amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33"})

这给了我想要的IP地址[x.x.x.x]输出.

and this give me the ip address [x.x.x.x] output that I want.

但是,如果我使用golang查询

However, if I query using the golang query

var SliceIP []NfInstance

db.C(COLLECTION).Find(bson.M{
                      "nfType": "AMF",
                      "amfInfo.amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33"}
                      ).Distinct("ipv4Addresses", &SliceIP)

我得到一个空数组,而不是数组中的IP地址字符串.在数据库中,我的json文档为

I'm getting an empty array instead of the the IP address string in an array. In the database i have the json document as

{
    "nfinstanceID": "3fa85f64-5717-4562-b3fc-2c963f66af33",
    "nfType": [
        "AMF"
    ],
    "nfStatus": [
        "REGISTERED"
    ],
    "sNssais": [
        {
            "sst": 1,
            "sd": "sd1"
        }
    ],
    "nsiList": [
        "string"
    ],
    "ipv4Addresses": [
        "198.51.100.300"
    ],
    "allowedNssais": [
        {
            "sst": 1,
            "sd": "sd1"
        }
    ],
    "amfInfo": {
        "amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33",
        "taiList": [
            {
                "plmnId": {
                    "mcc": "244",
                    "mnc": "38"
                },
                "tac": "string"
            }
        ],
        "n2InterfaceAmfInfo": {
            "ipv4EndpointAddress": [
                "198.51.100.105"
            ]
        }
    }
}

Mongodb命令行查询如下

Mongodb command line query look like this

> db.nfinstances.distinct("ipv4Addresses",{"nfType":"AMF", "amfInfo.amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33"})

mongodb Output:

[ "198.51.100.300" ]

我期望使用bson.M获得相同的输出

The same output I am expecting using the bson.M

任何人都可以帮助找到问题吗?

Can anyone help find the problem?

推荐答案

Query.Distinct() 解组不同的列表,而不是完整的文档(等效的MongoDB查询也返回值,而不是文档).

Query.Distinct() unmarshals the list of distinct values, not complete documents (the equivalent MongoDB query also returns values, not documents).

因此只需将不同的IP解组为[]string类型的值(并且永远不要忘记处理错误):

So simply unmarshal the distinct IPs into a value of type []string (and also never forget about handling errors):

var ips []string

err := db.C(COLLECTION).Find(bson.M{
    "nfType":           "AMF",
    "amfInfo.amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33",
}).Distinct("ipv4Addresses", &ips)
if err != nil {
    // handle error
}

这篇关于如何从MongoDb查询中编写go bson.M的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆