小编典典

如何在golang中编写bson形式的mongo查询?

go

我可以使用命令行查询查询mongodb集合以基于nfType和最小距离获取ipv4Addresses

db.nfinstancesdb.aggregate([
  {
    "$match": {
      "nfType": "AMF"
    }
  },
  {
    "$unwind": "$ipv4Addresses"
  },
  {
    $group: {
      "_id": "$distance",
      "ipv4Addresses": {
        "$addToSet": "$ipv4Addresses"
      }
    }
  },
  {
    "$sort": {
      "_id": 1
    }
  },
  {
    "$limit": 1
  }
])

这使输出预期为

[{"_id": 10,"ipv4Addresses": ["172.16.0.11","172.16.0.10"]}]

如何在Go上编写上述查询的bson形式?

我在下面的函数中执行了操作,但是获取了所有ipv4Addresses而不是上面的结果。

func (m *NfInstanceDataAccess) FindIp(nfType string) ([]NfInstance, error) {
    var ip []NfInstance

    collection := db.C(COLLECTION)
    pipeline := mongo.Pipeline{
        {{"$match", bson.D{
            {"nfType", "AMF"},
        }}},
        {{"$unwind", "$ipv4Addresses"}},
        {{"$group", bson.D{
            {"_id", "$distance"},
            {"ipv4Addresses", bson.D{
                {"$addToSet", "$ipv4Addresses"},
            }},
        }}},
        {{"$sort", bson.D{
            {"_id", 1},
        }}},
        {{"$limit", 1}},
    }

    cursor, err := collection.Aggregate(context.Background(), pipeline)
    defer cursor.Close(context.Background())
    for cursor.Next(context.Background()) {
        var ip []NfInstance
        err := cursor.Decode(&ip)
        if err != nil {
            log.Fatal(err)
        }
        //fmt.Println(doc)
    }
    return ip, nil
}

我的收藏有以下物品

{
    "nfInstanceID": "1",
    "nfType": [
      "AMF"
    ],
    "nfStatus": [
      "REGISTERED"
    ],
    "ipv4Addresses": [
      "172.16.0.10"
    ],
    "distance": 10
  },
  {
    "nfInstanceID": "2",
    "nfType": [
      "UPF"
    ],
    "nfStatus": [
      "REGISTERED"
    ],
    "ipv4Addresses": [
      "172.16.0.20"
    ],
    "distance": 20
  },
  {
    "nfInstanceID": "3",
    "nfType": [
      "AMF"
    ],
    "nfStatus": [
      "REGISTERED"
    ],
    "ipv4Addresses": [
      "172.16.0.30"
    ],
    "distance": 30
  },
  {
    "nfInstanceID": "4",
    "nfType": [
      "AMF"
    ],
    "nfStatus": [
      "REGISTERED"
    ],
    "ipv4Addresses": [
      "172.16.0.11"
    ],
    "distance": 10
  }

我期望输出相同或相似。


阅读 922

收藏
2020-07-02

共1个答案

小编典典

您的golang代码存在的问题是您没有分组。

您可以利用Pipe它来准备管道以进行聚合:

pipe := db.C(COLLECTION).Pipe([]bson.M{
    {"$match":  bson.M{"nfType": "AMF"}},
    {"$unwind": "$ipv4Addresses"},
    {"$group":  bson.M{
                       "_id": "$distance",
                       "ipv4Addresses": bson.M{"$addToSet": "$ipv4Addresses"},
                      }},
    {"$sort": bson.M{"_id": 1}},
    {"$limit": 1},

})

err := pipe.All(&ip)
2020-07-02