Home >Backend Development >Golang >How to Ignore Nulls When Unmarshaling MongoDB Documents in Go?
Ignoring Nulls During MongoDB Document Unmarshaling
Mongo-Go-Driver provides several approaches to ignore nulls when unmarshalling MongoDB documents into Go structs.
1. Custom Decoders for Specific Types
2. "Type-Neutral" Null-Aware Decoders
Code Sample:
// Nullaware decoder for all types, setting null values to zero values type NullawareDecoder struct { DefDecoder bsoncodec.ValueDecoder ZeroValue reflect.Value } // Decodes null values to zero values, otherwise delegates to the default decoder func (nd *NullawareDecoder) DecodeValue(dctx bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { if vr.Type() == bsontype.Null { if !val.CanSet() { return errors.New("value not settable") } if err := vr.ReadNull(); err != nil { return err } val.Set(nd.ZeroValue) return nil } return nd.DefDecoder.DecodeValue(dctx, vr, val) } // Register NullawareDecoder for desired types rb := bson.NewRegistryBuilder() rb.RegisterDecoder(reflect.TypeOf(""), &NullawareDecoder{bson.DefaultRegistry.LookupDecoder(reflect.TypeOf("")), reflect.ValueOf("")}) // ... (register for other types as needed) // Use the registry within a ClientOptions instance clientOpts := options.Client(). ApplyURI("mongodb://localhost:27017/"). SetRegistry(rb.Build()) // Initialize MongoDB client with customized registry to ignore nulls client, err := mongo.Connect(ctx, clientOpts)
The above is the detailed content of How to Ignore Nulls When Unmarshaling MongoDB Documents in Go?. For more information, please follow other related articles on the PHP Chinese website!