In v2, the options builder pattern has changed from setting data directly on an options object to maintaining a slice of setter functions. While standard usage like options.Find().SetBatchSize(1) remains the same, you must change how you handle advanced scenarios.
Modifying fields after building
Instead of direct assignment, create a custom setter function and append it to the Opts slice.
Creating a slice of options
When using options as elements in a slice, use the options.Lister[T] type instead of a pointer to the options struct.
Creating options from a builder
To extract a concrete options struct from a builder, you must iterate through the Opts slice and apply each setter to a new instance of the options struct.
// v2: Modifying fields after building
opts := options.Find().SetBatchSize(1)
maxAwaitTimeSetter := func(opts *options.FindOptions) error {
if opts.MaxAwaitTime == nil {
opts.MaxAwaitTime = &defaultMaxAwaitTime
}
return nil
}
opts.Opts = append(opts.Opts, maxAwaitTimeSetter)
// v2: Creating a slice of options
opts1 := options.Find().SetBatchSize(1)
opts2 := options.Find().SetComment("foo")
opts := []options.Lister[options.FindOptions]{opts1, opts2}
_, err := coll.Find(context.TODO(), bson.D{{"x", 1"}}, opts...)
// v2: Creating options from builder
var opts options.FindOptions
for _, set := range options.Find().SetBatchSize(1).Opts {
_ = set(&opts)
}
return findOptionAdder{option: &opts}