dongzhi4239 2019-06-25 09:53
浏览 130
已采纳

为什么mongo-go-driver聚合结果对象键返回为“ Key”

I want to group some data with mongo-go-driver using aggregate, but the json result confused me, because the row key replaced with "Key" and and the real key become the "Key"s value

var result primitive.A
pipeline := mongo.Pipeline{{{"$group", bson.D{{"_id", "$nis"}}}}}
cursor, err := db.NilaiUH.Aggregate(context.TODO(), pipeline)
cursor.All(context.Background(), &result)
json.NewEncoder(w).Encode(&result)

Here is the result

[
  [
    {
      "Key": "_id",
      "Value": 15100
    }
  ],
  [
    {
      "Key": "_id",
      "Value": 15101
    }
  ]
]
  • 写回答

1条回答 默认 最新

  • douchen1924 2019-06-25 11:40
    关注

    The new version of MongoDB driver treated the empty interface as an array of keys and values instead of a mapping between strings and empty interfaces. I have corrected the issue use the following code:

    // register custom codec registry to handle empty interfaces
    rb := bson.NewRegistryBuilder()
    rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.M{}))
    
    client, err := mongo.NewClient(options.Client().ApplyURI(url).SetRegistry(rb.Build()))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 求一款能支持ios15以上的屏蔽越狱插件。比较好用的
  • ¥15 C++ QT对比内存字符(形式不定)
  • ¥30 C++第三方库libiconv 远程安装协助
  • ¥15 https://github.com/youlaitech/vue3-element-admin/blob/master/src/store/modules/user.ts 这2句代码如何理解
  • ¥15 duilib开发文本字串超过长度显示
  • ¥20 mysql的.ibd文件为啥那么多
  • ¥15 C++中采用栈和BFS算法求解迷宫问题
  • ¥15 关于#java#的问题:这是跳转失败出现的界面这是哪个出现问题的servlet(开发工具-ide)
  • ¥15 EBS R12费用采购跨月冲销
  • ¥15 python中用mplfinance如何做到多股同列?