【问题标题】:Decode Mongo 128-bit Decimal to Go解码 Mongo 128-bit Decimal to Go
【发布时间】:2022-01-20 15:14:54
【问题描述】:

在 Mongodb 我有这个字段:

units: NumberDecimal('1'),

映射到:

Units         float64 `json:"units"`

我正在尝试从 Go 读取数据:

    var result dbo.Invoice
    coll := client.Database("hobbit").Collection("customer")
    filter := bson.D{{"_id", code}}
    err = coll.FindOne(context.TODO(), filter).Decode(&result)
    if err != nil {
        if err == mongo.ErrNoDocuments {
            return model.Customer{}, fmt.Errorf("invoice %s not found", code)
        }
        return model.Customer{}, fmt.Errorf("reading invoice %s from database: %s", code, err)
    }

我得到了这个错误

Error: error un-marshalling invoice F-3945: error decoding key lines.0.units: cannot decode 128-bit decimal into a float32 or float64 type

我尝试用bsoncodec注册转换:

registryBuilder := bsoncodec.NewRegistryBuilder()
registryBuilder.RegisterTypeMapEntry(bsontype.Decimal128, reflect.TypeOf(float64(0)))

仍然出现同样的错误

【问题讨论】:

  • 我看到了您的编辑,您是否在没有 registryBuilder 的情况下尝试过,只是为了看看它是否有效?
  • 它与primitive.Decimal128一起工作:D

标签: mongodb go


【解决方案1】:

应该是

Units primitive.Decimal128 `json:"units"`

这是NumberDecimal的数据类型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-06
    • 2013-10-01
    • 2019-02-25
    • 2016-09-13
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2019-07-31
    相关资源
    最近更新 更多