Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Mongo 128-bit Decimal to Go

Tags:

mongodb

go

In Mongodb I have this field:

units: NumberDecimal('1'),

Mapped in Go to:

Units         float64 `json:"units"`

I'm trying to read the data from Go with:

    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)
    }

And I get this error

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

I tried to register the conversion with bsoncodec:

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

And still getting the same error

like image 694
p3quod Avatar asked Jan 25 '26 09:01

p3quod


1 Answers

It should be

Units primitive.Decimal128 `json:"units"`

That's the data type for NumberDecimal

like image 132
Wolfgang Avatar answered Jan 27 '26 00:01

Wolfgang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!