【问题标题】:How to marshal json string to bson document for writing to MongoDB?如何将 json 字符串编组到 bson 文档以写入 MongoDB?
【发布时间】:2016-09-30 06:45:08
【问题描述】:

我在看的是Document.parse()

在 golang 中,这允许我直接从 json 创建 bson 吗?我不想为编组创建中间 Go 结构

【问题讨论】:

标签: mongodb go mgo


【解决方案1】:

gopkg.in/mgo.v2/bson 包有一个名为 UnmarshalJSON 的函数,它完全符合您的要求。

data 参数应该将 JSON 字符串保存为 []byte 值。

 func UnmarshalJSON(data []byte, value interface{}) error

UnmarshalJSON 解组一个 JSON 值,该值可能包含 BSON 的扩展 JSON 规范中定义的非标准语法。

例子:

var bdoc interface{}
err = bson.UnmarshalJSON([]byte(`{"id": 1,"name": "A green door","price": 12.50,"tags": ["home", "green"]}`),&bdoc)
if err != nil {
    panic(err)
}
err = c.Insert(&bdoc)

if err != nil {
    panic(err)
}

【讨论】:

  • 第二个参数值呢,文档似乎没有详细说明它需要是什么类型?从我对 go 的理解来看,interface{} 相当于 C 中的 void * 或 java 中的 Object ?指向 unmarshalJSON 示例的指针会更好
  • void* 和 interface{} 有很大区别。当变量为 void* 时,无法找出变量的类型。而 interface{} 知道类型。
【解决方案2】:

mongo-go-driver 有一个函数 bson.UnmarshalExtJSON 可以完成这项工作。

示例如下:

var doc interface{}
err := bson.UnmarshalExtJSON([]byte(`{"foo":"bar"}`), true, &doc)
if err != nil {
    // handle error
}

【讨论】:

    【解决方案3】:

    不再有办法直接使用受支持的库(例如 mongo-go-driver)来执行此操作。您需要根据 bson 规范编写自己的转换器。

    【讨论】:

      【解决方案4】:

      我不想为编组创建中间 Go 结构

      如果您确实想要/需要创建中间 Go BSON 结构,您可以使用转换模块,例如 github.com/sindbach/json-to-bson-go。例如:

      import (
          "fmt"
          "github.com/sindbach/json-to-bson-go/convert"
          "github.com/sindbach/json-to-bson-go/options"
      )
      
      func main() {
          doc := `{"foo": "buildfest", "bar": {"$numberDecimal":"2021"} }`
          opt := options.NewOptions()
          result, _ := convert.Convert([]byte(doc), opt)
          fmt.Println(result)
      }
      

      将产生输出:

      package main
      
      import "go.mongodb.org/mongo-driver/bson/primitive"
      
      type Example struct {
          Foo string               `bson:"foo"`
          Bar primitive.Decimal128 `bson:"bar"`
      }
      

      此模块与the official MongoDB Go driver 兼容,如您所见,它支持Extended JSON formats

      您也可以访问https://json-to-bson-map.netlify.app 来试用该模块。您可以粘贴 JSON 文档,然后查看 Go BSON 结构作为输出。

      【讨论】:

        猜你喜欢
        • 2021-11-26
        • 2015-09-27
        • 2018-12-25
        • 1970-01-01
        • 2022-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-06
        相关资源
        最近更新 更多