Mongo go driver: uint always marshals to bson int64

The documentation for the bson package states the following:

uint, uint32, and uint64 marshal to a BSON int32 if the value is between math.MinInt32 and math.MaxInt32, inclusive, and BSON int64 otherwise.

But for some reason, uint always marshals into bson int64. On the other hand int behaves as excepted.

Here you can find a working example of the problem. It seems like a really simple thing I am probably missing, so I am currently not opening an issue.

Hi @Yishai_Berg ! Thank you for bringing this to our attention. I’ve created GODRIVER-3071 to correct the documentation. The Go Driver will only use this “minimum int” logic when defined:

package main

import (
	"bytes"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/bsonrw"
)

func main() {
	type foo struct {
		Bar uint32
	}

	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewBSONValueWriter(buf)
	if err != nil {
		panic(err)
	}

	enc, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	enc.IntMinSize()

	err = enc.Encode(foo{2})
	if err != nil {
		panic(err)
	}

	// Print the BSON document as Extended JSON by converting it to bson.Raw.
	fmt.Println(bson.Raw(buf.Bytes()).String())
}
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.