1.修改代码适配阿里云的服务器

This commit is contained in:
whm
2026-03-17 14:27:32 +08:00
parent 826617d737
commit 20e7f3a65d
1777 changed files with 775041 additions and 10 deletions

View File

@@ -0,0 +1,170 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/internal/optionsutil"
)
// AggregateOptions represents arguments that can be used to configure an
// Aggregate operation.
//
// See corresponding setter methods for documentation.
type AggregateOptions struct {
AllowDiskUse *bool
BatchSize *int32
BypassDocumentValidation *bool
Collation *Collation
MaxAwaitTime *time.Duration
Comment any
Hint any
Let any
Custom bson.M
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// AggregateOptionsBuilder contains options to configure aggregate operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type AggregateOptionsBuilder struct {
Opts []func(*AggregateOptions) error
}
// Aggregate creates a new AggregateOptions instance.
func Aggregate() *AggregateOptionsBuilder {
return &AggregateOptionsBuilder{}
}
// List returns a list of AggergateOptions setter functions.
func (ao *AggregateOptionsBuilder) List() []func(*AggregateOptions) error {
return ao.Opts
}
// SetAllowDiskUse sets the value for the AllowDiskUse field. If true, the operation can write to temporary
// files in the _tmp subdirectory of the database directory path on the server. The default value is false.
func (ao *AggregateOptionsBuilder) SetAllowDiskUse(b bool) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.AllowDiskUse = &b
return nil
})
return ao
}
// SetBatchSize sets the value for the BatchSize field. Specifies the maximum number of documents
// to be included in each batch returned by the server.
func (ao *AggregateOptionsBuilder) SetBatchSize(i int32) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.BatchSize = &i
return nil
})
return ao
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes
// executed as part of the operation will opt out of document-level validation on the server. The default value
// is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about
// document validation.
func (ao *AggregateOptionsBuilder) SetBypassDocumentValidation(b bool) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return ao
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (ao *AggregateOptionsBuilder) SetCollation(c *Collation) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.Collation = c
return nil
})
return ao
}
// SetMaxAwaitTime sets the value for the MaxAwaitTime field. Specifies maximum amount of time
// that the server should wait for new documents to satisfy a tailable cursor query.
func (ao *AggregateOptionsBuilder) SetMaxAwaitTime(d time.Duration) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.MaxAwaitTime = &d
return nil
})
return ao
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be included in
// server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil,
// which means that no comment will be included in the logs.
func (ao *AggregateOptionsBuilder) SetComment(comment any) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.Comment = comment
return nil
})
return ao
}
// SetHint sets the value for the Hint field. Specifies the index to use for the aggregation. This should
// either be the index name as a string or the index specification as a document. The hint does not apply to
// $lookup and $graphLookup aggregation stages. The driver will return an error if the hint parameter
// is a multi-key map. The default value is nil, which means that no hint will be sent.
func (ao *AggregateOptionsBuilder) SetHint(h any) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.Hint = h
return nil
})
return ao
}
// SetLet sets the value for the Let field. Specifies parameters for the aggregate expression. This
// option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using this
// option. This must be a document mapping parameter names to values. Values must be constant or closed
// expressions that do not reference document fields. Parameters can then be accessed as variables in
// an aggregate expression context (e.g. "$$var").
func (ao *AggregateOptionsBuilder) SetLet(let any) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.Let = let
return nil
})
return ao
}
// SetCustom sets the value for the Custom field. Key-value pairs of the BSON map should correlate
// with desired option names and values. Values must be Marshalable. Custom options may conflict
// with non-custom options, and custom options bypass client-side validation. Prefer using non-custom
// options where possible.
func (ao *AggregateOptionsBuilder) SetCustom(c bson.M) *AggregateOptionsBuilder {
ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error {
opts.Custom = c
return nil
})
return ao
}

View File

@@ -0,0 +1,176 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"crypto/tls"
"net/http"
"time"
"go.mongodb.org/mongo-driver/v2/internal/httputil"
)
// AutoEncryptionOptions represents arguments used to configure auto encryption/decryption behavior for a mongo.Client
// instance.
//
// Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic
// encryption is not supported for operations on a database or view, and operations that are not bypassed will result
// in error. Too bypass automatic encryption for all operations, set BypassAutoEncryption=true.
//
// Auto encryption requires the authenticated user to have the listCollections privilege action.
//
// If automatic encryption fails on an operation, use a MongoClient configured with bypassAutoEncryption=true and use
// ClientEncryption.encrypt() to manually encrypt values.
//
// Enabling In-Use Encryption reduces the maximum document and message size (using a maxBsonObjectSize of 2MiB and
// maxMessageSizeBytes of 6MB) and may have a negative performance impact.
//
// See corresponding setter methods for documentation.
type AutoEncryptionOptions struct {
KeyVaultClientOptions *ClientOptions
KeyVaultNamespace string
KmsProviders map[string]map[string]any
SchemaMap map[string]any
BypassAutoEncryption *bool
ExtraOptions map[string]any
TLSConfig map[string]*tls.Config
HTTPClient *http.Client
EncryptedFieldsMap map[string]any
BypassQueryAnalysis *bool
KeyExpiration *time.Duration
}
// AutoEncryption creates a new AutoEncryptionOptions configured with default values.
func AutoEncryption() *AutoEncryptionOptions {
return &AutoEncryptionOptions{
HTTPClient: httputil.DefaultHTTPClient,
}
}
// SetKeyVaultClientOptions specifies options for the client used to communicate with the key vault collection.
//
// If this is set, it is used to create an internal mongo.Client.
// Otherwise, if the target mongo.Client being configured has an unlimited connection pool size (i.e. maxPoolSize=0),
// it is reused to interact with the key vault collection.
// Otherwise, if the target mongo.Client has a limited connection pool size, a separate internal mongo.Client is used
// (and created if necessary). The internal mongo.Client may be shared during automatic encryption (if
// BypassAutomaticEncryption is false). The internal mongo.Client is configured with the same options as the target
// mongo.Client except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
func (a *AutoEncryptionOptions) SetKeyVaultClientOptions(opts *ClientOptions) *AutoEncryptionOptions {
a.KeyVaultClientOptions = opts
return a
}
// SetKeyVaultNamespace specifies the namespace of the key vault collection. This is required.
func (a *AutoEncryptionOptions) SetKeyVaultNamespace(ns string) *AutoEncryptionOptions {
a.KeyVaultNamespace = ns
return a
}
// SetKmsProviders specifies options for KMS providers. This is required.
func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string]any) *AutoEncryptionOptions {
a.KmsProviders = providers
return a
}
// SetSchemaMap specifies a map from namespace to local schema document. Schemas supplied in the schemaMap only apply
// to configuring automatic encryption for Client-Side Field Level Encryption. Other validation rules in the JSON schema
// will not be enforced by the driver and will result in an error.
//
// Supplying a schemaMap provides more security than relying on JSON Schemas obtained from the server. It protects
// against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted
// data that should be encrypted.
func (a *AutoEncryptionOptions) SetSchemaMap(schemaMap map[string]any) *AutoEncryptionOptions {
a.SchemaMap = schemaMap
return a
}
// SetBypassAutoEncryption specifies whether or not auto encryption should be done.
//
// If this is unset or false and target mongo.Client being configured has an unlimited connection pool size
// (i.e. maxPoolSize=0), it is reused in the process of auto encryption.
// Otherwise, if the target mongo.Client has a limited connection pool size, a separate internal mongo.Client is used
// (and created if necessary). The internal mongo.Client may be shared for key vault operations (if KeyVaultClient is
// unset). The internal mongo.Client is configured with the same options as the target mongo.Client except minPoolSize
// is set to 0 and AutoEncryptionOptions is omitted.
func (a *AutoEncryptionOptions) SetBypassAutoEncryption(bypass bool) *AutoEncryptionOptions {
a.BypassAutoEncryption = &bypass
return a
}
// SetExtraOptions specifies a map of options to configure the mongocryptd process or mongo_crypt shared library.
//
// # Supported Extra Options
//
// "mongocryptdURI" - The mongocryptd URI. Allows setting a custom URI used to communicate with the
// mongocryptd process. The default is "mongodb://localhost:27020", which works with the default
// mongocryptd process spawned by the Client. Must be a string.
//
// "mongocryptdBypassSpawn" - If set to true, the Client will not attempt to spawn a mongocryptd
// process. Must be a bool.
//
// "mongocryptdSpawnPath" - The path used when spawning mongocryptd.
// Defaults to empty string and spawns mongocryptd from system path. Must be a string.
//
// "mongocryptdSpawnArgs" - Command line arguments passed when spawning mongocryptd.
// Defaults to ["--idleShutdownTimeoutSecs=60"]. Must be an array of strings.
//
// "cryptSharedLibRequired" - If set to true, Client creation will return an error if the
// crypt_shared library is not loaded. If unset or set to false, Client creation will not return an
// error if the crypt_shared library is not loaded. The default is unset. Must be a bool.
//
// "cryptSharedLibPath" - The crypt_shared library override path. This must be the path to the
// crypt_shared dynamic library file (for example, a .so, .dll, or .dylib file), not the directory
// that contains it. If the override path is a relative path, it will be resolved relative to the
// working directory of the process. If the override path is a relative path and the first path
// component is the literal string "$ORIGIN", the "$ORIGIN" component will be replaced by the
// absolute path to the directory containing the linked libmongocrypt library. Setting an override
// path disables the default system library search path. If an override path is specified but the
// crypt_shared library cannot be loaded, Client creation will return an error. Must be a string.
func (a *AutoEncryptionOptions) SetExtraOptions(extraOpts map[string]any) *AutoEncryptionOptions {
a.ExtraOptions = extraOpts
return a
}
// SetTLSConfig specifies tls.Config instances for each KMS provider to use to configure TLS on all connections created
// to the KMS provider.
func (a *AutoEncryptionOptions) SetTLSConfig(cfg map[string]*tls.Config) *AutoEncryptionOptions {
// This should only be used to set custom TLS configurations. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12.
a.TLSConfig = cfg
return a
}
// SetEncryptedFieldsMap specifies a map from namespace to local EncryptedFieldsMap document.
// EncryptedFieldsMap is used for Queryable Encryption.
func (a *AutoEncryptionOptions) SetEncryptedFieldsMap(ef map[string]any) *AutoEncryptionOptions {
a.EncryptedFieldsMap = ef
return a
}
// SetBypassQueryAnalysis specifies whether or not query analysis should be used for automatic encryption.
// Use this option when using explicit encryption with Queryable Encryption.
func (a *AutoEncryptionOptions) SetBypassQueryAnalysis(bypass bool) *AutoEncryptionOptions {
a.BypassQueryAnalysis = &bypass
return a
}
// SetKeyExpiration specifies duration for the key expiration. 0 or negative value means "never expire".
// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up.
func (a *AutoEncryptionOptions) SetKeyExpiration(expiration time.Duration) *AutoEncryptionOptions {
a.KeyExpiration = &expiration
return a
}

View File

@@ -0,0 +1,100 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// DefaultOrdered is the default value for the Ordered option in BulkWriteOptions.
var DefaultOrdered = true
// BulkWriteOptions represents arguments that can be used to configure a
// BulkWrite operation.
//
// See corresponding setter methods for documentation.
type BulkWriteOptions struct {
BypassDocumentValidation *bool
Comment any
Ordered *bool
Let any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// BulkWriteOptionsBuilder contains options to configure bulk write operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type BulkWriteOptionsBuilder struct {
Opts []func(*BulkWriteOptions) error
}
// BulkWrite creates a new *BulkWriteOptions instance.
func BulkWrite() *BulkWriteOptionsBuilder {
opts := &BulkWriteOptionsBuilder{}
opts = opts.SetOrdered(DefaultOrdered)
return opts
}
// List returns a list of BulkWriteOptions setter functions.
func (b *BulkWriteOptionsBuilder) List() []func(*BulkWriteOptions) error {
return b.Opts
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be included in
// server logs, profiling logs, and currentOp queries to help tracethe operation. The default value is nil,
// which means that no comment will be included in the logs.
func (b *BulkWriteOptionsBuilder) SetComment(comment any) *BulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error {
opts.Comment = comment
return nil
})
return b
}
// SetOrdered sets the value for the Ordered field. If true, no writes will be executed after one fails.
// The default value is true.
func (b *BulkWriteOptionsBuilder) SetOrdered(ordered bool) *BulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error {
opts.Ordered = &ordered
return nil
})
return b
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes
// executed as part of the operation will opt out of document-level validation on the server. The default value is
// false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document
// validation.
func (b *BulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) *BulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error {
opts.BypassDocumentValidation = &bypass
return nil
})
return b
}
// SetLet sets the value for the Let field. Let specifies parameters for all update and delete commands in the BulkWrite.
// This option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using this option.
// This must be a document mapping parameter names to values. Values must be constant or closed expressions that do not
// reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var").
func (b *BulkWriteOptionsBuilder) SetLet(let any) *BulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error {
opts.Let = &let
return nil
})
return b
}

View File

@@ -0,0 +1,183 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/v2/bson"
)
// ChangeStreamOptions represents arguments that can be used to configure a Watch operation.
//
// See corresponding setter methods for documentation.
type ChangeStreamOptions struct {
BatchSize *int32
Collation *Collation
Comment any
FullDocument *FullDocument
FullDocumentBeforeChange *FullDocument
MaxAwaitTime *time.Duration
ResumeAfter any
ShowExpandedEvents *bool
StartAtOperationTime *bson.Timestamp
StartAfter any
Custom bson.M
CustomPipeline bson.M
}
// ChangeStreamOptionsBuilder contains options to configure change stream
// operations. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type ChangeStreamOptionsBuilder struct {
Opts []func(*ChangeStreamOptions) error
}
// ChangeStream creates a new ChangeStreamOptions instance.
func ChangeStream() *ChangeStreamOptionsBuilder {
return &ChangeStreamOptionsBuilder{}
}
// List returns a list of ChangeStreamOptions setter functions.
func (cso *ChangeStreamOptionsBuilder) List() []func(*ChangeStreamOptions) error {
return cso.Opts
}
// SetBatchSize sets the value for the BatchSize field. Specifies the maximum number of documents to
// be included in each batch returned by the server.
func (cso *ChangeStreamOptionsBuilder) SetBatchSize(i int32) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.BatchSize = &i
return nil
})
return cso
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (cso *ChangeStreamOptionsBuilder) SetCollation(c Collation) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.Collation = &c
return nil
})
return cso
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be included in
// server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil,
// which means that no comment will be included in the logs.
func (cso *ChangeStreamOptionsBuilder) SetComment(comment any) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.Comment = comment
return nil
})
return cso
}
// SetFullDocument sets the value for the FullDocument field. Specifies how the updated document should be
// returned in change notifications for update operations. The default is options.Default, which means that
// only partial update deltas will be included in the change notification.
func (cso *ChangeStreamOptionsBuilder) SetFullDocument(fd FullDocument) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.FullDocument = &fd
return nil
})
return cso
}
// SetFullDocumentBeforeChange sets the value for the FullDocumentBeforeChange field. Specifies how the
// pre-update document should be returned in change notifications for update operations. The default
// is options.Off, which means that the pre-update document will not be included in the change notification.
func (cso *ChangeStreamOptionsBuilder) SetFullDocumentBeforeChange(fdbc FullDocument) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.FullDocumentBeforeChange = &fdbc
return nil
})
return cso
}
// SetMaxAwaitTime sets the value for the MaxAwaitTime field. The maximum amount of time that the server should
// wait for new documents to satisfy a tailable cursor query.
func (cso *ChangeStreamOptionsBuilder) SetMaxAwaitTime(d time.Duration) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.MaxAwaitTime = &d
return nil
})
return cso
}
// SetResumeAfter sets the value for the ResumeAfter field. Specifies a document specifying the logical starting
// point for the change stream. Only changes corresponding to an oplog entry immediately after the resume token
// will be returned. If this is specified, StartAtOperationTime and StartAfter must not be set.
func (cso *ChangeStreamOptionsBuilder) SetResumeAfter(rt any) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.ResumeAfter = rt
return nil
})
return cso
}
// SetShowExpandedEvents sets the value for the ShowExpandedEvents field. ShowExpandedEvents specifies whether
// the server will return an expanded list of change stream events. Additional events include: createIndexes,
// dropIndexes, modify, create, shardCollection, reshardCollection and refineCollectionShardKey. This option
// is only valid for MongoDB versions >= 6.0.
func (cso *ChangeStreamOptionsBuilder) SetShowExpandedEvents(see bool) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.ShowExpandedEvents = &see
return nil
})
return cso
}
// SetStartAtOperationTime sets the value for the StartAtOperationTime field. If specified, the change stream
// will only return changes that occurred at or after the given timestamp.
// If this is specified, ResumeAfter and StartAfter must not be set.
func (cso *ChangeStreamOptionsBuilder) SetStartAtOperationTime(t *bson.Timestamp) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.StartAtOperationTime = t
return nil
})
return cso
}
// SetStartAfter sets the value for the StartAfter field. Sets a document specifying the logical starting
// point for the change stream. This is similar to the ResumeAfter option, but allows a resume token from
// an "invalidate" notification to be used. This allows a change stream on a collection to be resumed after
// the collection has been dropped and recreated or renamed. Only changes corresponding to an oplog entry
// immediately after the specified token will be returned. If this is specified, ResumeAfter and
// StartAtOperationTime must not be set. This option is only valid for MongoDB versions >= 4.1.1.
func (cso *ChangeStreamOptionsBuilder) SetStartAfter(sa any) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.StartAfter = sa
return nil
})
return cso
}
// SetCustom sets the value for the Custom field. Key-value pairs of the BSON map should correlate
// with desired option names and values. Values must be Marshalable. Custom options may conflict
// with non-custom options, and custom options bypass client-side validation. Prefer using non-custom
// options where possible.
func (cso *ChangeStreamOptionsBuilder) SetCustom(c bson.M) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.Custom = c
return nil
})
return cso
}
// SetCustomPipeline sets the value for the CustomPipeline field. Key-value pairs of the BSON map
// should correlate with desired option names and values. Values must be Marshalable. Custom pipeline
// options bypass client-side validation. Prefer using non-custom options where possible.
func (cso *ChangeStreamOptionsBuilder) SetCustomPipeline(cp bson.M) *ChangeStreamOptionsBuilder {
cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error {
opts.CustomPipeline = cp
return nil
})
return cso
}

View File

@@ -0,0 +1,127 @@
// Copyright (C) MongoDB, Inc. 2024-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/internal/optionsutil"
"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)
// ClientBulkWriteOptions represents options that can be used to configure a client-level BulkWrite operation.
//
// See corresponding setter methods for documentation.
type ClientBulkWriteOptions struct {
BypassDocumentValidation *bool
Comment any
Ordered *bool
Let any
WriteConcern *writeconcern.WriteConcern
VerboseResults *bool
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// ClientBulkWriteOptionsBuilder contains options to configure client-level bulk
// write operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type ClientBulkWriteOptionsBuilder struct {
Opts []func(*ClientBulkWriteOptions) error
}
// ClientBulkWrite creates a new *ClientBulkWriteOptions instance.
func ClientBulkWrite() *ClientBulkWriteOptionsBuilder {
opts := &ClientBulkWriteOptionsBuilder{}
opts = opts.SetOrdered(DefaultOrdered)
return opts
}
// List returns a list of ClientBulkWriteOptions setter functions.
func (b *ClientBulkWriteOptionsBuilder) List() []func(*ClientBulkWriteOptions) error {
return b.Opts
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be included in
// server logs, profiling logs, and currentOp queries to help tracethe operation. The default value is nil,
// which means that no comment will be included in the logs.
func (b *ClientBulkWriteOptionsBuilder) SetComment(comment any) *ClientBulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error {
opts.Comment = comment
return nil
})
return b
}
// SetOrdered sets the value for the Ordered field. If true, no writes will be executed after one fails.
// The default value is true.
func (b *ClientBulkWriteOptionsBuilder) SetOrdered(ordered bool) *ClientBulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error {
opts.Ordered = &ordered
return nil
})
return b
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes
// executed as part of the operation will opt out of document-level validation on the server. The default
// value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information
// about document validation.
func (b *ClientBulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) *ClientBulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error {
opts.BypassDocumentValidation = &bypass
return nil
})
return b
}
// SetLet sets the value for the Let field. Let specifies parameters for all update and delete commands in the BulkWrite.
// This must be a document mapping parameter names to values. Values must be constant or closed expressions that do not
// reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var").
func (b *ClientBulkWriteOptionsBuilder) SetLet(let any) *ClientBulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error {
opts.Let = &let
return nil
})
return b
}
// SetWriteConcern sets the value for the WriteConcern field. Specifies the write concern for
// operations in the transaction. The default value is nil, which means that the default
// write concern of the session used to start the transaction will be used.
func (b *ClientBulkWriteOptionsBuilder) SetWriteConcern(wc *writeconcern.WriteConcern) *ClientBulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error {
opts.WriteConcern = wc
return nil
})
return b
}
// SetVerboseResults sets the value for the VerboseResults field. Specifies whether detailed
// results for each successful operation should be included in the returned BulkWriteResult.
// The defaults value is false.
func (b *ClientBulkWriteOptionsBuilder) SetVerboseResults(verboseResults bool) *ClientBulkWriteOptionsBuilder {
b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error {
opts.VerboseResults = &verboseResults
return nil
})
return b
}

View File

@@ -0,0 +1,158 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"crypto/tls"
"fmt"
"net/http"
"time"
"go.mongodb.org/mongo-driver/v2/internal/httputil"
)
// ClientEncryptionOptions represents all possible arguments used to configure a ClientEncryption instance.
//
// See corresponding setter methods for documentation.
type ClientEncryptionOptions struct {
KeyVaultNamespace string
KmsProviders map[string]map[string]any
TLSConfig map[string]*tls.Config
HTTPClient *http.Client
KeyExpiration *time.Duration
}
// ClientEncryptionOptionsBuilder contains options to configure client
// encryption operations. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type ClientEncryptionOptionsBuilder struct {
Opts []func(*ClientEncryptionOptions) error
}
// ClientEncryption creates a new ClientEncryptionOptions instance.
func ClientEncryption() *ClientEncryptionOptionsBuilder {
return &ClientEncryptionOptionsBuilder{
Opts: []func(*ClientEncryptionOptions) error{
func(arg *ClientEncryptionOptions) error {
arg.HTTPClient = httputil.DefaultHTTPClient
return nil
},
},
}
}
// List returns a list of ClientEncryptionOptions setter functions.
func (c *ClientEncryptionOptionsBuilder) List() []func(*ClientEncryptionOptions) error {
return c.Opts
}
// SetKeyVaultNamespace specifies the namespace of the key vault collection. This is required.
func (c *ClientEncryptionOptionsBuilder) SetKeyVaultNamespace(ns string) *ClientEncryptionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error {
opts.KeyVaultNamespace = ns
return nil
})
return c
}
// SetKmsProviders specifies options for KMS providers. This is required.
func (c *ClientEncryptionOptionsBuilder) SetKmsProviders(providers map[string]map[string]any) *ClientEncryptionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error {
opts.KmsProviders = providers
return nil
})
return c
}
// SetTLSConfig specifies tls.Config instances for each KMS provider to use to configure TLS on all connections created
// to the KMS provider.
//
// This should only be used to set custom TLS configurations. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12.
func (c *ClientEncryptionOptionsBuilder) SetTLSConfig(cfg map[string]*tls.Config) *ClientEncryptionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error {
opts.TLSConfig = cfg
return nil
})
return c
}
// SetKeyExpiration specifies duration for the key expiration. 0 or negative value means "never expire".
// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up.
func (c *ClientEncryptionOptionsBuilder) SetKeyExpiration(expiration time.Duration) *ClientEncryptionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error {
opts.KeyExpiration = &expiration
return nil
})
return c
}
// BuildTLSConfig specifies tls.Config options for each KMS provider to use to configure TLS on all connections created
// to the KMS provider. The input map should contain a mapping from each KMS provider to a document containing the necessary
// options, as follows:
//
// {
// "kmip": {
// "tlsCertificateKeyFile": "foo.pem",
// "tlsCAFile": "fooCA.pem"
// }
// }
//
// Currently, the following TLS options are supported:
//
// 1. "tlsCertificateKeyFile" (or "sslClientCertificateKeyFile"): The "tlsCertificateKeyFile" option specifies a path to
// the client certificate and private key, which must be concatenated into one file.
//
// 2. "tlsCertificateKeyFilePassword" (or "sslClientCertificateKeyPassword"): Specify the password to decrypt the client
// private key file (e.g. "tlsCertificateKeyFilePassword=password").
//
// 3. "tlsCaFile" (or "sslCertificateAuthorityFile"): Specify the path to a single or bundle of certificate authorities
// to be considered trusted when making a TLS connection (e.g. "tlsCaFile=/path/to/caFile").
//
// This should only be used to set custom TLS options. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12.
func BuildTLSConfig(tlsOpts map[string]any) (*tls.Config, error) {
// use TLS min version 1.2 to enforce more secure hash algorithms and advanced cipher suites
cfg := &tls.Config{MinVersion: tls.VersionTLS12}
for name := range tlsOpts {
var err error
switch name {
case "tlsCertificateKeyFile", "sslClientCertificateKeyFile":
clientCertPath, ok := tlsOpts[name].(string)
if !ok {
return nil, fmt.Errorf("expected %q value to be of type string, got %T", name, tlsOpts[name])
}
// apply custom key file password if found, otherwise use empty string
if keyPwd, found := tlsOpts["tlsCertificateKeyFilePassword"].(string); found {
_, err = addClientCertFromConcatenatedFile(cfg, clientCertPath, keyPwd)
} else if keyPwd, found := tlsOpts["sslClientCertificateKeyPassword"].(string); found {
_, err = addClientCertFromConcatenatedFile(cfg, clientCertPath, keyPwd)
} else {
_, err = addClientCertFromConcatenatedFile(cfg, clientCertPath, "")
}
case "tlsCertificateKeyFilePassword", "sslClientCertificateKeyPassword":
continue
case "tlsCAFile", "sslCertificateAuthorityFile":
caPath, ok := tlsOpts[name].(string)
if !ok {
return nil, fmt.Errorf("expected %q value to be of type string, got %T", name, tlsOpts[name])
}
err = addCACertFromFile(cfg, caPath)
default:
return nil, fmt.Errorf("unrecognized TLS option %v", name)
}
if err != nil {
return nil, err
}
}
return cfg, nil
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,105 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)
// CollectionOptions represents arguments that can be used to configure a Collection.
//
// See corresponding setter methods for documentation.
type CollectionOptions struct {
ReadConcern *readconcern.ReadConcern
WriteConcern *writeconcern.WriteConcern
ReadPreference *readpref.ReadPref
BSONOptions *BSONOptions
Registry *bson.Registry
}
// CollectionOptionsBuilder contains options to configure a Collection instance.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type CollectionOptionsBuilder struct {
Opts []func(*CollectionOptions) error
}
// Collection creates a new CollectionOptions instance.
func Collection() *CollectionOptionsBuilder {
return &CollectionOptionsBuilder{}
}
// List returns a list of CollectionOptions setter functions.
func (c *CollectionOptionsBuilder) List() []func(*CollectionOptions) error {
return c.Opts
}
// SetReadConcern sets the value for the ReadConcern field. ReadConcern is the read concern to use for
// operations executed on the Collection. The default value is nil, which means that the read concern
// of the Database used to configure the Collection will be used.
func (c *CollectionOptionsBuilder) SetReadConcern(rc *readconcern.ReadConcern) *CollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CollectionOptions) error {
opts.ReadConcern = rc
return nil
})
return c
}
// SetWriteConcern sets the value for the WriteConcern field. WriteConcern is the write concern to
// use for operations executed on the Collection. The default value is nil, which means that the write
// concern of the Database used to configure the Collection will be used.
func (c *CollectionOptionsBuilder) SetWriteConcern(wc *writeconcern.WriteConcern) *CollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CollectionOptions) error {
opts.WriteConcern = wc
return nil
})
return c
}
// SetReadPreference sets the value for the ReadPreference field. ReadPreference is the read preference
// to use for operations executed on the Collection. The default value is nil, which means that the
// read preference of the Database used to configure the Collection will be used.
func (c *CollectionOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *CollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CollectionOptions) error {
opts.ReadPreference = rp
return nil
})
return c
}
// SetBSONOptions configures optional BSON marshaling and unmarshaling behavior. BSONOptions configures
// optional BSON marshaling and unmarshaling behavior.
func (c *CollectionOptionsBuilder) SetBSONOptions(bopts *BSONOptions) *CollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CollectionOptions) error {
opts.BSONOptions = bopts
return nil
})
return c
}
// SetRegistry sets the value for the Registry field. Registry is the BSON registry to marshal and
// unmarshal documents for operations executed on the Collection. The default value is nil, which
// means that the registry of the Database used to configure the Collection will be used.
func (c *CollectionOptionsBuilder) SetRegistry(r *bson.Registry) *CollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CollectionOptions) error {
opts.Registry = r
return nil
})
return c
}

View File

@@ -0,0 +1,107 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// CountOptions represents arguments that can be used to configure a
// CountDocuments operation.
//
// See corresponding setter methods for documentation.
type CountOptions struct {
Collation *Collation
Comment any
Hint any
Limit *int64
Skip *int64
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// CountOptionsBuilder contains options to configure count operations. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type CountOptionsBuilder struct {
Opts []func(*CountOptions) error
}
// Count creates a new CountOptions instance.
func Count() *CountOptionsBuilder {
return &CountOptionsBuilder{}
}
// List returns a list of CountOptions setter functions.
func (co *CountOptionsBuilder) List() []func(*CountOptions) error {
return co.Opts
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (co *CountOptionsBuilder) SetCollation(c *Collation) *CountOptionsBuilder {
co.Opts = append(co.Opts, func(opts *CountOptions) error {
opts.Collation = c
return nil
})
return co
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be included
// in server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil,
// which means that no comment will be included in the logs.
func (co *CountOptionsBuilder) SetComment(comment any) *CountOptionsBuilder {
co.Opts = append(co.Opts, func(opts *CountOptions) error {
opts.Comment = comment
return nil
})
return co
}
// SetHint sets the value for the Hint field. Specifies the index to use for the aggregation. This should
// either be the index name as a string or the index specification as a document. The driver will return
// an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint
// will be sent.
func (co *CountOptionsBuilder) SetHint(h any) *CountOptionsBuilder {
co.Opts = append(co.Opts, func(opts *CountOptions) error {
opts.Hint = h
return nil
})
return co
}
// SetLimit sets the value for the Limit field. Specifies the maximum number of documents to count. The
// default value is 0, which means that there is no limit and all documents matching the filter will be
// counted.
func (co *CountOptionsBuilder) SetLimit(i int64) *CountOptionsBuilder {
co.Opts = append(co.Opts, func(opts *CountOptions) error {
opts.Limit = &i
return nil
})
return co
}
// SetSkip sets the value for the Skip field. Specifies the number of documents to skip before counting.
// The default value is 0.
func (co *CountOptionsBuilder) SetSkip(i int64) *CountOptionsBuilder {
co.Opts = append(co.Opts, func(opts *CountOptions) error {
opts.Skip = &i
return nil
})
return co
}

View File

@@ -0,0 +1,413 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
)
// DefaultIndexOptions represents the default arguments for a collection to
// apply on new indexes. This type can be used when creating a new collection
// through the CreateCollectionOptions.SetDefaultIndexOptions method.
//
// See corresponding setter methods for documentation.
type DefaultIndexOptions struct {
StorageEngine any
}
// DefaultIndexOptionsBuilder contains options to configure default index
// operations. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type DefaultIndexOptionsBuilder struct {
Opts []func(*DefaultIndexOptions) error
}
// DefaultIndex creates a new DefaultIndexOptions instance.
func DefaultIndex() *DefaultIndexOptionsBuilder {
return &DefaultIndexOptionsBuilder{}
}
// List returns a list of DefaultIndexOptions setter functions.
func (d *DefaultIndexOptionsBuilder) List() []func(*DefaultIndexOptions) error {
return d.Opts
}
// SetStorageEngine sets the value for the StorageEngine field. Specifies the storage engine to use for
// the index. The value must be a document in the form {<storage engine name>: <options>}. The default
// value is nil, which means that the default storage engine will be used.
func (d *DefaultIndexOptionsBuilder) SetStorageEngine(storageEngine any) *DefaultIndexOptionsBuilder {
d.Opts = append(d.Opts, func(opts *DefaultIndexOptions) error {
opts.StorageEngine = storageEngine
return nil
})
return d
}
// TimeSeriesOptions specifies arguments on a time-series collection.
//
// See corresponding setter methods for documentation.
type TimeSeriesOptions struct {
TimeField string
MetaField *string
Granularity *string
BucketMaxSpan *time.Duration
BucketRounding *time.Duration
}
// TimeSeriesOptionsBuilder contains options to configure timeseries operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type TimeSeriesOptionsBuilder struct {
Opts []func(*TimeSeriesOptions) error
}
// TimeSeries creates a new TimeSeriesOptions instance.
func TimeSeries() *TimeSeriesOptionsBuilder {
return &TimeSeriesOptionsBuilder{}
}
// List returns a list of TimeSeriesOptions setter functions.
func (tso *TimeSeriesOptionsBuilder) List() []func(*TimeSeriesOptions) error {
return tso.Opts
}
// SetTimeField sets the value for the TimeField. TimeField is the top-level field to be used
// for time. Inserted documents must have this field, and the field must be of the BSON UTC
// datetime type (0x9).
func (tso *TimeSeriesOptionsBuilder) SetTimeField(timeField string) *TimeSeriesOptionsBuilder {
tso.Opts = append(tso.Opts, func(opts *TimeSeriesOptions) error {
opts.TimeField = timeField
return nil
})
return tso
}
// SetMetaField sets the value for the MetaField. MetaField is the name of the top-level field
// describing the series. This field is used to group related data and may be of any BSON type,
// except for array. This name may not be the same as the TimeField or _id. This field is optional.
func (tso *TimeSeriesOptionsBuilder) SetMetaField(metaField string) *TimeSeriesOptionsBuilder {
tso.Opts = append(tso.Opts, func(opts *TimeSeriesOptions) error {
opts.MetaField = &metaField
return nil
})
return tso
}
// SetGranularity sets the value for Granularity. Granularity is the granularity of time-series data.
// Allowed granularity options are "seconds", "minutes" and "hours". This field is optional.
func (tso *TimeSeriesOptionsBuilder) SetGranularity(granularity string) *TimeSeriesOptionsBuilder {
tso.Opts = append(tso.Opts, func(opts *TimeSeriesOptions) error {
opts.Granularity = &granularity
return nil
})
return tso
}
// SetBucketMaxSpan sets the value for BucketMaxSpan. BucketMaxSpan is the maximum range of time
// values for a bucket. The time.Duration is rounded down to the nearest second and applied as
// the command option: "bucketRoundingSeconds". This field is optional.
func (tso *TimeSeriesOptionsBuilder) SetBucketMaxSpan(dur time.Duration) *TimeSeriesOptionsBuilder {
tso.Opts = append(tso.Opts, func(opts *TimeSeriesOptions) error {
opts.BucketMaxSpan = &dur
return nil
})
return tso
}
// SetBucketRounding sets the value for BucketRounding. BucketRounding is used to determine the
// minimum time boundary when opening a new bucket by rounding the first timestamp down to the next
// multiple of this value. The time.Duration is rounded down to the nearest second and applied as
// the command option: "bucketRoundingSeconds". This field is optional.
func (tso *TimeSeriesOptionsBuilder) SetBucketRounding(dur time.Duration) *TimeSeriesOptionsBuilder {
tso.Opts = append(tso.Opts, func(opts *TimeSeriesOptions) error {
opts.BucketRounding = &dur
return nil
})
return tso
}
// CreateCollectionOptions represents arguments that can be used to configure a
// CreateCollection operation.
//
// See corresponding setter methods for documentation.
type CreateCollectionOptions struct {
Capped *bool
Collation *Collation
ChangeStreamPreAndPostImages any
DefaultIndexOptions *DefaultIndexOptionsBuilder
MaxDocuments *int64
SizeInBytes *int64
StorageEngine any
ValidationAction *string
ValidationLevel *string
Validator any
ExpireAfterSeconds *int64
TimeSeriesOptions *TimeSeriesOptionsBuilder
EncryptedFields any
ClusteredIndex any
}
// CreateCollectionOptionsBuilder contains options to configure a new
// collection. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type CreateCollectionOptionsBuilder struct {
Opts []func(*CreateCollectionOptions) error
}
// CreateCollection creates a new CreateCollectionOptions instance.
func CreateCollection() *CreateCollectionOptionsBuilder {
return &CreateCollectionOptionsBuilder{}
}
// List returns a list of CreateCollectionOptions setter functions.
func (c *CreateCollectionOptionsBuilder) List() []func(*CreateCollectionOptions) error {
return c.Opts
}
// SetCapped sets the value for the Capped field. Specifies if the collection is capped
// (see https://www.mongodb.com/docs/manual/core/capped-collections/). If true, the SizeInBytes
// option must also be specified. The default value is false.
func (c *CreateCollectionOptionsBuilder) SetCapped(capped bool) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.Capped = &capped
return nil
})
return c
}
// SetCollation sets the value for the Collation field. Specifies the default
// collation for the new collection. The default value is nil.
func (c *CreateCollectionOptionsBuilder) SetCollation(collation *Collation) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.Collation = collation
return nil
})
return c
}
// SetChangeStreamPreAndPostImages sets the value for the ChangeStreamPreAndPostImages field.
// Specifies how change streams opened against the collection can return pre- and post-images of
// updated documents. The value must be a document in the form {<option name>: <options>}. This
// option is only valid for MongoDB versions >= 6.0. The default value is nil, which means that
// change streams opened against the collection will not return pre- and post-images of updated
// documents in any way.
func (c *CreateCollectionOptionsBuilder) SetChangeStreamPreAndPostImages(csppi any) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.ChangeStreamPreAndPostImages = &csppi
return nil
})
return c
}
// SetDefaultIndexOptions sets the value for the DefaultIndexOptions field.
// Specifies a default configuration for indexes on the collection. The default
// value is nil, meaning indexes will be configured using server defaults.
func (c *CreateCollectionOptionsBuilder) SetDefaultIndexOptions(iopts *DefaultIndexOptionsBuilder) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.DefaultIndexOptions = iopts
return nil
})
return c
}
// SetMaxDocuments sets the value for the MaxDocuments field. Specifies the maximum number of documents
// allowed in a capped collection. The limit specified by the SizeInBytes option takes precedence over
// this option. If a capped collection reaches its size limit, old documents will be removed, regardless
// of the number of documents in the collection. The default value is 0, meaning the maximum number of
// documents is unbounded.
func (c *CreateCollectionOptionsBuilder) SetMaxDocuments(max int64) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.MaxDocuments = &max
return nil
})
return c
}
// SetSizeInBytes sets the value for the SizeInBytes field. Specifies the maximum size in bytes for a
// capped collection. The default value is 0.
func (c *CreateCollectionOptionsBuilder) SetSizeInBytes(size int64) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.SizeInBytes = &size
return nil
})
return c
}
// SetStorageEngine sets the value for the StorageEngine field. Specifies the storage engine to use for
// the index. The value must be a document in the form {<storage engine name>: <options>}. The default
// value is nil, which means that the default storage engine will be used.
func (c *CreateCollectionOptionsBuilder) SetStorageEngine(storageEngine any) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.StorageEngine = &storageEngine
return nil
})
return c
}
// SetValidationAction sets the value for the ValidationAction field. Specifies what should happen if a
// document being inserted does not pass validation. Valid values are "error" and "warn". See
// https://www.mongodb.com/docs/manual/core/schema-validation/#accept-or-reject-invalid-documents for more
// information. The default value is "error".
func (c *CreateCollectionOptionsBuilder) SetValidationAction(action string) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.ValidationAction = &action
return nil
})
return c
}
// SetValidationLevel sets the value for the ValidationLevel field. Specifies how strictly the server applies
// validation rules to existing documents in the collection during update operations. Valid values are "off",
// "strict", and "moderate". See https://www.mongodb.com/docs/manual/core/schema-validation/#existing-documents
// for more information. The default value is "strict".
func (c *CreateCollectionOptionsBuilder) SetValidationLevel(level string) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.ValidationLevel = &level
return nil
})
return c
}
// SetValidator sets the value for the Validator field. Sets a document specifying validation rules for the
// collection. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about
// schema validation. The default value is nil, meaning no validator will be used for the collection.
func (c *CreateCollectionOptionsBuilder) SetValidator(validator any) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.Validator = validator
return nil
})
return c
}
// SetExpireAfterSeconds sets the value for the ExpireAfterSeconds field. Specifies value
// indicating after how many seconds old time-series data should be deleted.
// See https://www.mongodb.com/docs/manual/reference/command/create/ for supported options,
// and https://www.mongodb.com/docs/manual/core/timeseries-collections/ for more information
// on time-series collections.
//
// This option is only valid for MongoDB versions >= 5.0
func (c *CreateCollectionOptionsBuilder) SetExpireAfterSeconds(eas int64) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.ExpireAfterSeconds = &eas
return nil
})
return c
}
// SetTimeSeriesOptions sets the options for time-series collections. Specifies options for specifying
// a time-series collection. See https://www.mongodb.com/docs/manual/reference/command/create/ for
// supported options, and https://www.mongodb.com/docs/manual/core/timeseries-collections/ for more
// information on time-series collections.
//
// This option is only valid for MongoDB versions >= 5.0
func (c *CreateCollectionOptionsBuilder) SetTimeSeriesOptions(timeSeriesOpts *TimeSeriesOptionsBuilder) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.TimeSeriesOptions = timeSeriesOpts
return nil
})
return c
}
// SetEncryptedFields sets the encrypted fields for encrypted collections.
//
// This option is only valid for MongoDB versions >= 6.0
func (c *CreateCollectionOptionsBuilder) SetEncryptedFields(encryptedFields any) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.EncryptedFields = encryptedFields
return nil
})
return c
}
// SetClusteredIndex sets the value for the ClusteredIndex field which is used
// to create a collection with a clustered index.
//
// This option is only valid for MongoDB versions >= 5.3
func (c *CreateCollectionOptionsBuilder) SetClusteredIndex(clusteredIndex any) *CreateCollectionOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error {
opts.ClusteredIndex = clusteredIndex
return nil
})
return c
}
// CreateViewOptions represents arguments that can be used to configure a
// CreateView operation.
//
// See corresponding setter methods for documentation.
type CreateViewOptions struct {
Collation *Collation
}
// CreateViewOptionsBuilder contains options to configure a new view. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type CreateViewOptionsBuilder struct {
Opts []func(*CreateViewOptions) error
}
// CreateView creates an new CreateViewOptions instance.
func CreateView() *CreateViewOptionsBuilder {
return &CreateViewOptionsBuilder{}
}
// List returns a list of TimeSeriesOptions setter functions.
func (c *CreateViewOptionsBuilder) List() []func(*CreateViewOptions) error {
return c.Opts
}
// SetCollation sets the value for the Collation field. Specifies the default
// collation for the new collection. The default value is nil.
func (c *CreateViewOptionsBuilder) SetCollation(collation *Collation) *CreateViewOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateViewOptions) error {
opts.Collation = collation
return nil
})
return c
}

View File

@@ -0,0 +1,107 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// DataKeyOptions represents all possible options used to create a new data key.
//
// See corresponding setter methods for documentation.
type DataKeyOptions struct {
MasterKey any
KeyAltNames []string
KeyMaterial []byte
}
// DataKeyOptionsBuilder contains options to configure DataKey operations. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type DataKeyOptionsBuilder struct {
Opts []func(*DataKeyOptions) error
}
// DataKey creates a new DataKeyOptions instance.
func DataKey() *DataKeyOptionsBuilder {
return &DataKeyOptionsBuilder{}
}
// List returns a list of DataKey setter functions.
func (dk *DataKeyOptionsBuilder) List() []func(*DataKeyOptions) error {
return dk.Opts
}
// SetMasterKey specifies a KMS-specific key used to encrypt the new data key.
//
// If being used with a local KMS provider, this option is not applicable and should not be specified.
//
// For the AWS, Azure, and GCP KMS providers, this option is required and must be a document. For each, the value of the
// "endpoint" or "keyVaultEndpoint" must be a host name with an optional port number (e.g. "foo.com" or "foo.com:443").
//
// When using AWS, the document must have the format:
//
// {
// region: <string>,
// key: <string>, // The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
// endpoint: Optional<string> // An alternate host identifier to send KMS requests to.
// }
//
// If unset, the "endpoint" defaults to "kms.<region>.amazonaws.com".
//
// When using Azure, the document must have the format:
//
// {
// keyVaultEndpoint: <string>, // A host identifier to send KMS requests to.
// keyName: <string>,
// keyVersion: Optional<string> // A specific version of the named key.
// }
//
// If unset, "keyVersion" defaults to the key's primary version.
//
// When using GCP, the document must have the format:
//
// {
// projectId: <string>,
// location: <string>,
// keyRing: <string>,
// keyName: <string>,
// keyVersion: Optional<string>, // A specific version of the named key.
// endpoint: Optional<string> // An alternate host identifier to send KMS requests to.
// }
//
// If unset, "keyVersion" defaults to the key's primary version and "endpoint" defaults to "cloudkms.googleapis.com".
func (dk *DataKeyOptionsBuilder) SetMasterKey(masterKey any) *DataKeyOptionsBuilder {
dk.Opts = append(dk.Opts, func(opts *DataKeyOptions) error {
opts.MasterKey = masterKey
return nil
})
return dk
}
// SetKeyAltNames specifies an optional list of string alternate names used to reference a key. If a key is created'
// with alternate names, encryption may refer to the key by a unique alternate name instead of by _id.
func (dk *DataKeyOptionsBuilder) SetKeyAltNames(keyAltNames []string) *DataKeyOptionsBuilder {
dk.Opts = append(dk.Opts, func(opts *DataKeyOptions) error {
opts.KeyAltNames = keyAltNames
return nil
})
return dk
}
// SetKeyMaterial will set a custom keyMaterial to DataKeyOptions which can be used to encrypt data. If omitted,
// keyMaterial is generated form a cryptographically secure random source. "Key Material" is used interchangeably
// with "dataKey" and "Data Encryption Key" (DEK).
func (dk *DataKeyOptionsBuilder) SetKeyMaterial(keyMaterial []byte) *DataKeyOptionsBuilder {
dk.Opts = append(dk.Opts, func(opts *DataKeyOptions) error {
opts.KeyMaterial = keyMaterial
return nil
})
return dk
}

View File

@@ -0,0 +1,106 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)
// DatabaseOptions represents arguments that can be used to configure a
// database.
//
// See corresponding setter methods for documentation.
type DatabaseOptions struct {
ReadConcern *readconcern.ReadConcern
WriteConcern *writeconcern.WriteConcern
ReadPreference *readpref.ReadPref
BSONOptions *BSONOptions
Registry *bson.Registry
}
// DatabaseOptionsBuilder contains options to configure a database object. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type DatabaseOptionsBuilder struct {
Opts []func(*DatabaseOptions) error
}
// Database creates a new DatabaseOptions instance.
func Database() *DatabaseOptionsBuilder {
return &DatabaseOptionsBuilder{}
}
// List returns a list of DatabaseOptions setter functions.
func (d *DatabaseOptionsBuilder) List() []func(*DatabaseOptions) error {
return d.Opts
}
// SetReadConcern sets the value for the ReadConcern field. ReadConcern is the read concern
// to use for operations executed on the Database. The default value is nil, which means that
// the read concern of the Client used to configure the Database will be used.
func (d *DatabaseOptionsBuilder) SetReadConcern(rc *readconcern.ReadConcern) *DatabaseOptionsBuilder {
d.Opts = append(d.Opts, func(opts *DatabaseOptions) error {
opts.ReadConcern = rc
return nil
})
return d
}
// SetWriteConcern sets the value for the WriteConcern field. WriteConcern is the write concern
// to use for operations executed on the Database. The default value is nil, which means that
// the write concern of the Client used to configure the Database will be used.
func (d *DatabaseOptionsBuilder) SetWriteConcern(wc *writeconcern.WriteConcern) *DatabaseOptionsBuilder {
d.Opts = append(d.Opts, func(opts *DatabaseOptions) error {
opts.WriteConcern = wc
return nil
})
return d
}
// SetReadPreference sets the value for the ReadPreference field. ReadPreference is the read
// preference to use for operations executed on the Database. The default value is nil, which
// means that the read preference of the Client used to configure the Database will be used.
func (d *DatabaseOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *DatabaseOptionsBuilder {
d.Opts = append(d.Opts, func(opts *DatabaseOptions) error {
opts.ReadPreference = rp
return nil
})
return d
}
// SetBSONOptions configures optional BSON marshaling and unmarshaling behavior. BSONOptions
// configures optional BSON marshaling and unmarshaling behavior.
func (d *DatabaseOptionsBuilder) SetBSONOptions(bopts *BSONOptions) *DatabaseOptionsBuilder {
d.Opts = append(d.Opts, func(opts *DatabaseOptions) error {
opts.BSONOptions = bopts
return nil
})
return d
}
// SetRegistry sets the value for the Registry field. Registry is the BSON registry to marshal and
// unmarshal documents for operations executed on the Database. The default value is nil, which
// means that the registry of the Client used to configure the Database will be used.
func (d *DatabaseOptionsBuilder) SetRegistry(r *bson.Registry) *DatabaseOptionsBuilder {
d.Opts = append(d.Opts, func(opts *DatabaseOptions) error {
opts.Registry = r
return nil
})
return d
}

View File

@@ -0,0 +1,191 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// DeleteOneOptions represents arguments that can be used to configure DeleteOne
// operations.
//
// See corresponding setter methods for documentation.
type DeleteOneOptions struct {
Collation *Collation
Comment any
Hint any
Let any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// DeleteOneOptionsBuilder contains options to configure DeleteOne operations. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type DeleteOneOptionsBuilder struct {
Opts []func(*DeleteOneOptions) error
}
// DeleteOne creates a new DeleteOneOptions instance.
func DeleteOne() *DeleteOneOptionsBuilder {
return &DeleteOneOptionsBuilder{}
}
// List returns a list of DeleteOneOptions setter functions.
func (do *DeleteOneOptionsBuilder) List() []func(*DeleteOneOptions) error {
return do.Opts
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (do *DeleteOneOptionsBuilder) SetCollation(c *Collation) *DeleteOneOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error {
opts.Collation = c
return nil
})
return do
}
// SetComment sets the value for the Comment field. Specifies a string or document that will
// be included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (do *DeleteOneOptionsBuilder) SetComment(comment any) *DeleteOneOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error {
opts.Comment = comment
return nil
})
return do
}
// SetHint sets the value for the Hint field. Specifies the index to use for the
// operation. This should either be the index name as a string or the index
// specification as a document. This option is only valid for MongoDB versions
// >= 4.4. Server versions < 4.4 will return an error if this option is
// specified. The driver will return an error if this option is specified during
// an unacknowledged write operation. The driver will return an error if the
// hint parameter is a multi-key map. The default value is nil, which means that
// no hint will be sent.
func (do *DeleteOneOptionsBuilder) SetHint(hint any) *DeleteOneOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error {
opts.Hint = hint
return nil
})
return do
}
// SetLet sets the value for the Let field. Specifies parameters for the delete expression. This
// option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using
// this option. This must be a document mapping parameter names to values. Values must be constant
// or closed expressions that do not reference document fields. Parameters can then be accessed as
// variables in an aggregate expression context (e.g. "$$var").
func (do *DeleteOneOptionsBuilder) SetLet(let any) *DeleteOneOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error {
opts.Let = let
return nil
})
return do
}
// DeleteManyOptions represents arguments that can be used to configure DeleteMany
// operations.
//
// See corresponding setter methods for documentation.
type DeleteManyOptions struct {
Collation *Collation
Comment any
Hint any
Let any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// DeleteManyOptionsBuilder contains options to configure DeleteMany operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type DeleteManyOptionsBuilder struct {
Opts []func(*DeleteManyOptions) error
}
// DeleteMany creates a new DeleteManyOptions instance.
func DeleteMany() *DeleteManyOptionsBuilder {
return &DeleteManyOptionsBuilder{}
}
// List returns a list of DeleteOneOptions setter functions.
func (do *DeleteManyOptionsBuilder) List() []func(*DeleteManyOptions) error {
return do.Opts
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (do *DeleteManyOptionsBuilder) SetCollation(c *Collation) *DeleteManyOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error {
opts.Collation = c
return nil
})
return do
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (do *DeleteManyOptionsBuilder) SetComment(comment any) *DeleteManyOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error {
opts.Comment = comment
return nil
})
return do
}
// SetHint sets the value for the Hint field. Specifies the index to use for the
// operation. This should either be the index name as a string or the index
// specification as a document. This option is only valid for MongoDB versions
// >= 4.4. Server versions < 4.4 will return an error if this option is
// specified. The driver will return an error if this option is specified during
// an unacknowledged write operation. The driver will return an error if the
// hint parameter is a multi-key map. The default value is nil, which means that
// no hint will be sent.
func (do *DeleteManyOptionsBuilder) SetHint(hint any) *DeleteManyOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error {
opts.Hint = hint
return nil
})
return do
}
// SetLet sets the value for the Let field. Specifies parameters for the delete expression.
// This option is only valid for MongoDB versions >= 5.0. Older servers will report an error
// for using this option. This must be a document mapping parameter names to values. Values
// must be constant or closed expressions that do not reference document fields. Parameters
// can then be accessed as variables in an aggregate expression context (e.g. "$$var").
func (do *DeleteManyOptionsBuilder) SetLet(let any) *DeleteManyOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error {
opts.Let = let
return nil
})
return do
}

View File

@@ -0,0 +1,85 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// DistinctOptions represents arguments that can be used to configure a Distinct
// operation.
//
// See corresponding setter methods for documentation.
type DistinctOptions struct {
Collation *Collation
Comment any
Hint any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// DistinctOptionsBuilder contains options to configure distinct operations. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type DistinctOptionsBuilder struct {
Opts []func(*DistinctOptions) error
}
// Distinct creates a new DistinctOptions instance.
func Distinct() *DistinctOptionsBuilder {
return &DistinctOptionsBuilder{}
}
// List returns a list of DistinctArg setter functions.
func (do *DistinctOptionsBuilder) List() []func(*DistinctOptions) error {
return do.Opts
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (do *DistinctOptionsBuilder) SetCollation(c *Collation) *DistinctOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DistinctOptions) error {
opts.Collation = c
return nil
})
return do
}
// SetComment sets the value for the Comment field. Specifies a string or document that
// will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included
// in the logs.
func (do *DistinctOptionsBuilder) SetComment(comment any) *DistinctOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DistinctOptions) error {
opts.Comment = comment
return nil
})
return do
}
// SetHint specifies the index to use for the operation. This should either be
// the index name as a string or the index specification as a document. This
// option is only valid for MongoDB versions >= 7.1. Previous server versions
// will return an error if an index hint is specified. Distinct returns an error
// if the hint parameter is a multi-key map. The default value is nil, which
// means that no index hint will be sent.
//
// SetHint sets the Hint field.
func (do *DistinctOptionsBuilder) SetHint(hint any) *DistinctOptionsBuilder {
do.Opts = append(do.Opts, func(opts *DistinctOptions) error {
opts.Hint = hint
return nil
})
return do
}

View File

@@ -0,0 +1,8 @@
// Copyright (C) MongoDB, Inc. 2022-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Package options defines the optional configurations for the MongoDB Go Driver.
package options

View File

@@ -0,0 +1,45 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// DropCollectionOptions represents arguments that can be used to configure a
// Drop operation.
//
// See corresponding setter methods for documentation.
type DropCollectionOptions struct {
EncryptedFields any
}
// DropCollectionOptionsBuilder contains options to configure collection drop
// operations. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type DropCollectionOptionsBuilder struct {
Opts []func(*DropCollectionOptions) error
}
// DropCollection creates a new DropCollectionOptions instance.
func DropCollection() *DropCollectionOptionsBuilder {
return &DropCollectionOptionsBuilder{}
}
// List returns a list of DropCollectionOptions setter functions.
func (d *DropCollectionOptionsBuilder) List() []func(*DropCollectionOptions) error {
return d.Opts
}
// SetEncryptedFields sets the encrypted fields for encrypted collections.
//
// This option is only valid for MongoDB versions >= 6.0
func (d *DropCollectionOptionsBuilder) SetEncryptedFields(encryptedFields any) *DropCollectionOptionsBuilder {
d.Opts = append(d.Opts, func(opts *DropCollectionOptions) error {
opts.EncryptedFields = encryptedFields
return nil
})
return d
}

View File

@@ -0,0 +1,355 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/bson"
)
// These constants specify valid values for QueryType
// QueryType is used for Queryable Encryption.
const (
QueryTypeEquality string = "equality"
)
// RangeOptions specifies index options for a Queryable Encryption field supporting "range" queries.
//
// See corresponding setter methods for documentation.
type RangeOptions struct {
Min *bson.RawValue
Max *bson.RawValue
Sparsity *int64
TrimFactor *int32
Precision *int32
}
// RangeOptionsBuilder contains options to configure RangeOptions for queryable
// encryption. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type RangeOptionsBuilder struct {
Opts []func(*RangeOptions) error
}
// Range creates a new RangeOptions instance.
func Range() *RangeOptionsBuilder {
return &RangeOptionsBuilder{}
}
// List returns a list of RangeOptions setter functions.
func (ro *RangeOptionsBuilder) List() []func(*RangeOptions) error {
return ro.Opts
}
// SetMin sets the range index minimum value.
func (ro *RangeOptionsBuilder) SetMin(min bson.RawValue) *RangeOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *RangeOptions) error {
opts.Min = &min
return nil
})
return ro
}
// SetMax sets the range index maximum value.
func (ro *RangeOptionsBuilder) SetMax(max bson.RawValue) *RangeOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *RangeOptions) error {
opts.Max = &max
return nil
})
return ro
}
// SetSparsity sets the range index sparsity.
func (ro *RangeOptionsBuilder) SetSparsity(sparsity int64) *RangeOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *RangeOptions) error {
opts.Sparsity = &sparsity
return nil
})
return ro
}
// SetTrimFactor sets the range index trim factor.
func (ro *RangeOptionsBuilder) SetTrimFactor(trimFactor int32) *RangeOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *RangeOptions) error {
opts.TrimFactor = &trimFactor
return nil
})
return ro
}
// SetPrecision sets the range index precision.
func (ro *RangeOptionsBuilder) SetPrecision(precision int32) *RangeOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *RangeOptions) error {
opts.Precision = &precision
return nil
})
return ro
}
// TextOptions specifies index options for a Queryable Encryption field supporting "text" queries.
//
// See corresponding setter methods for documentation.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
type TextOptions struct {
Substring *SubstringOptions
Prefix *PrefixOptions
Suffix *SuffixOptions
CaseSensitive bool
DiacriticSensitive bool
}
// SubstringOptions specifies options to support substring queries.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
type SubstringOptions struct {
StrMaxLength int32
StrMinQueryLength int32
StrMaxQueryLength int32
}
// PrefixOptions specifies options to support prefix queries.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
type PrefixOptions struct {
StrMinQueryLength int32
StrMaxQueryLength int32
}
// SuffixOptions specifies options to support suffix queries.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
type SuffixOptions struct {
StrMinQueryLength int32
StrMaxQueryLength int32
}
// TextOptionsBuilder contains options to configure TextOptions for queryable
// encryption. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
type TextOptionsBuilder struct {
Opts []func(*TextOptions) error
}
// Text creates a new TextOptions instance.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
func Text() *TextOptionsBuilder {
return &TextOptionsBuilder{}
}
// List returns a list of TextOptions setter functions.
func (to *TextOptionsBuilder) List() []func(*TextOptions) error {
return to.Opts
}
// SetSubstring sets the text index substring value.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
func (to *TextOptionsBuilder) SetSubstring(substring SubstringOptions) *TextOptionsBuilder {
to.Opts = append(to.Opts, func(opts *TextOptions) error {
opts.Substring = &substring
return nil
})
return to
}
// SetPrefix sets the text index prefix value.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
func (to *TextOptionsBuilder) SetPrefix(prefix PrefixOptions) *TextOptionsBuilder {
to.Opts = append(to.Opts, func(opts *TextOptions) error {
opts.Prefix = &prefix
return nil
})
return to
}
// SetSuffix sets the text index suffix value.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
func (to *TextOptionsBuilder) SetSuffix(suffix SuffixOptions) *TextOptionsBuilder {
to.Opts = append(to.Opts, func(opts *TextOptions) error {
opts.Suffix = &suffix
return nil
})
return to
}
// SetCaseSensitive sets the text index caseSensitive value.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
func (to *TextOptionsBuilder) SetCaseSensitive(caseSensitive bool) *TextOptionsBuilder {
to.Opts = append(to.Opts, func(opts *TextOptions) error {
opts.CaseSensitive = caseSensitive
return nil
})
return to
}
// SetDiacriticSensitive sets the text index diacriticSensitive value.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
func (to *TextOptionsBuilder) SetDiacriticSensitive(diacriticSensitive bool) *TextOptionsBuilder {
to.Opts = append(to.Opts, func(opts *TextOptions) error {
opts.DiacriticSensitive = diacriticSensitive
return nil
})
return to
}
// EncryptOptions represents arguments to explicitly encrypt a value.
//
// See corresponding setter methods for documentation.
type EncryptOptions struct {
KeyID *bson.Binary
KeyAltName *string
Algorithm string
QueryType string
ContentionFactor *int64
RangeOptions *RangeOptionsBuilder
TextOptions *TextOptionsBuilder
}
// EncryptOptionsBuilder contains options to configure Encryptopts for
// queryeable encryption. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type EncryptOptionsBuilder struct {
Opts []func(*EncryptOptions) error
}
// List returns a list of EncryptOptions setter functions.
func (e *EncryptOptionsBuilder) List() []func(*EncryptOptions) error {
return e.Opts
}
// Encrypt creates a new EncryptOptions instance.
func Encrypt() *EncryptOptionsBuilder {
return &EncryptOptionsBuilder{}
}
// SetKeyID specifies an _id of a data key. This should be a UUID (a bson.Binary with subtype 4).
func (e *EncryptOptionsBuilder) SetKeyID(keyID bson.Binary) *EncryptOptionsBuilder {
e.Opts = append(e.Opts, func(opts *EncryptOptions) error {
opts.KeyID = &keyID
return nil
})
return e
}
// SetKeyAltName identifies a key vault document by 'keyAltName'.
func (e *EncryptOptionsBuilder) SetKeyAltName(keyAltName string) *EncryptOptionsBuilder {
e.Opts = append(e.Opts, func(opts *EncryptOptions) error {
opts.KeyAltName = &keyAltName
return nil
})
return e
}
// SetAlgorithm specifies an algorithm to use for encryption. This should be one of the following:
// - AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic
// - AEAD_AES_256_CBC_HMAC_SHA_512-Random
// - Indexed
// - Unindexed
// - Range
// This is required.
// Indexed and Unindexed are used for Queryable Encryption.
func (e *EncryptOptionsBuilder) SetAlgorithm(algorithm string) *EncryptOptionsBuilder {
e.Opts = append(e.Opts, func(opts *EncryptOptions) error {
opts.Algorithm = algorithm
return nil
})
return e
}
// SetQueryType specifies the intended query type. It is only valid to set if algorithm is "Indexed".
// This should be one of the following:
// - equality
// QueryType is used for Queryable Encryption.
func (e *EncryptOptionsBuilder) SetQueryType(queryType string) *EncryptOptionsBuilder {
e.Opts = append(e.Opts, func(opts *EncryptOptions) error {
opts.QueryType = queryType
return nil
})
return e
}
// SetContentionFactor specifies the contention factor. It is only valid to set if algorithm is "Indexed".
// ContentionFactor is used for Queryable Encryption.
func (e *EncryptOptionsBuilder) SetContentionFactor(contentionFactor int64) *EncryptOptionsBuilder {
e.Opts = append(e.Opts, func(opts *EncryptOptions) error {
opts.ContentionFactor = &contentionFactor
return nil
})
return e
}
// SetRangeOptions specifies the options to use for explicit encryption with range. It is only valid to set if algorithm is "range".
func (e *EncryptOptionsBuilder) SetRangeOptions(ro *RangeOptionsBuilder) *EncryptOptionsBuilder {
e.Opts = append(e.Opts, func(opts *EncryptOptions) error {
opts.RangeOptions = ro
return nil
})
return e
}
// SetTextOptions specifies the options to use for text queries.
//
// Beta: This is a preview feature and should only be used for experimental workloads.
// It is not intended for public use. It is subject to breaking changes.
func (e *EncryptOptionsBuilder) SetTextOptions(to *TextOptionsBuilder) *EncryptOptionsBuilder {
e.Opts = append(e.Opts, func(opts *EncryptOptions) error {
opts.TextOptions = to
return nil
})
return e
}

View File

@@ -0,0 +1,52 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// EstimatedDocumentCountOptions represents arguments that can be used to configure
// an EstimatedDocumentCount operation.
//
// See corresponding setter methods for documentation.
type EstimatedDocumentCountOptions struct {
Comment any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// EstimatedDocumentCountOptionsBuilder contains options to estimate document
// count. Each option can be set through setter functions. See documentation for
// each setter function for an explanation of the option.
type EstimatedDocumentCountOptionsBuilder struct {
Opts []func(*EstimatedDocumentCountOptions) error
}
// EstimatedDocumentCount creates a new EstimatedDocumentCountOptions instance.
func EstimatedDocumentCount() *EstimatedDocumentCountOptionsBuilder {
return &EstimatedDocumentCountOptionsBuilder{}
}
// List returns a list of CountOptions setter functions.
func (eco *EstimatedDocumentCountOptionsBuilder) List() []func(*EstimatedDocumentCountOptions) error {
return eco.Opts
}
// SetComment sets the value for the Comment field. Specifies a string or document
// that will be included in server logs, profiling logs, and currentOp queries to help
// trace the operation. The default is nil, which means that no comment will be
// included in the logs.
func (eco *EstimatedDocumentCountOptionsBuilder) SetComment(comment any) *EstimatedDocumentCountOptionsBuilder {
eco.Opts = append(eco.Opts, func(opts *EstimatedDocumentCountOptions) error {
opts.Comment = comment
return nil
})
return eco
}

View File

@@ -0,0 +1,910 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/v2/internal/optionsutil"
)
// FindOptions represents arguments that can be used to configure a Find
// operation.
//
// See corresponding setter methods for documentation.
type FindOptions struct {
AllowPartialResults *bool
Collation *Collation
Comment any
Hint any
Max any
MaxAwaitTime *time.Duration
Min any
OplogReplay *bool
Projection any
ReturnKey *bool
ShowRecordID *bool
Skip *int64
Sort any
// The above are in common with FindOneopts.
AllowDiskUse *bool
BatchSize *int32
CursorType *CursorType
Let any
Limit *int64
NoCursorTimeout *bool
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// FindOptionsBuilder represents functional options that configure an Findopts.
type FindOptionsBuilder struct {
Opts []func(*FindOptions) error
}
// Find creates a new FindOptions instance.
func Find() *FindOptionsBuilder {
return &FindOptionsBuilder{}
}
// List returns a list of FindOptions setter functions.
func (f *FindOptionsBuilder) List() []func(*FindOptions) error {
return f.Opts
}
// SetAllowDiskUse sets the value for the AllowDiskUse field. AllowDiskUse
// specifies whether the server can write temporary data to disk while executing
// the Find operation. This option is only valid for MongoDB versions >= 4.4.
// Server versions < 4.4 will return an error if this option is specified. The
// default value is false.
func (f *FindOptionsBuilder) SetAllowDiskUse(b bool) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.AllowDiskUse = &b
return nil
})
return f
}
// SetAllowPartialResults sets the value for the AllowPartialResults field. AllowPartial results
// specifies whether the Find operation on a sharded cluster can return partial results if some
// shards are down rather than returning an error. The default value is false.
func (f *FindOptionsBuilder) SetAllowPartialResults(b bool) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.AllowPartialResults = &b
return nil
})
return f
}
// SetBatchSize sets the value for the BatchSize field. BatchSize is the maximum number of documents
// to be included in each batch returned by the server.
func (f *FindOptionsBuilder) SetBatchSize(i int32) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.BatchSize = &i
return nil
})
return f
}
// SetCollation sets the value for the Collation field. Collation specifies a
// collation to use for string comparisons during the operation. The default
// value is nil, which means the default collation of the collection will be
// used.
func (f *FindOptionsBuilder) SetCollation(collation *Collation) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Collation = collation
return nil
})
return f
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default is nil, which means that no comment will be included in the logs.
func (f *FindOptionsBuilder) SetComment(comment any) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Comment = &comment
return nil
})
return f
}
// SetCursorType sets the value for the CursorType field. CursorType specifies the type of cursor
// that should be created for the operation. The default is NonTailable, which means that the
// cursor will be closed by the server when the last batch of documents is retrieved.
func (f *FindOptionsBuilder) SetCursorType(ct CursorType) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.CursorType = &ct
return nil
})
return f
}
// SetHint sets the value for the Hint field. Hint is the index to use for the Find operation.
// This should either be the index name as a string or the index specification as a document.
// The driver will return an error if the hint parameter is a multi-key map. The default
// value is nil, which means that no hint will be sent.
func (f *FindOptionsBuilder) SetHint(hint any) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Hint = hint
return nil
})
return f
}
// SetLet sets the value for the Let field. Let specifies parameters for the find expression.
// This option is only valid for MongoDB versions >= 5.0. Older servers will report an error
// for using this option. This must be a document mapping parameter names to values. Values
// must be constant or closed expressions that do not reference document fields. Parameters
// can then be accessed as variables in an aggregate expression context (e.g. "$$var").
func (f *FindOptionsBuilder) SetLet(let any) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Let = let
return nil
})
return f
}
// SetLimit sets the value for the Limit field. Limit is the maximum number of documents to return.
// The default value is 0, which means that all documents matching the filter will be returned.
// A negative limit specifies that the resulting documents should be returned in a single batch.
// The default value is 0.
func (f *FindOptionsBuilder) SetLimit(i int64) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Limit = &i
return nil
})
return f
}
// SetMax sets the value for the Max field. Max is a document specifying the exclusive upper bound
// for a specific index. The default value is nil, which means that there is no maximum value.
func (f *FindOptionsBuilder) SetMax(max any) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Max = max
return nil
})
return f
}
// SetMaxAwaitTime sets the value for the MaxAwaitTime field. MaxAwaitTime is
// the maximum amount of time that the server should wait for new documents to
// satisfy a tailable cursor query. This option is only valid for tailable await
// cursors (see the CursorType option for more information). For other cursor
// types, this option is ignored.
func (f *FindOptionsBuilder) SetMaxAwaitTime(d time.Duration) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.MaxAwaitTime = &d
return nil
})
return f
}
// SetMin sets the value for the Min field. Min is a document specifying the inclusive lower bound
// for a specific index. The default value is 0, which means that there is no minimum value.
func (f *FindOptionsBuilder) SetMin(min any) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Min = min
return nil
})
return f
}
// SetNoCursorTimeout sets the value for the NoCursorTimeout field. NoCursorTimeout specifies
// whether the cursor created by the operation will not timeout after a period of inactivity.
// The default value is false.
func (f *FindOptionsBuilder) SetNoCursorTimeout(b bool) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.NoCursorTimeout = &b
return nil
})
return f
}
// SetOplogReplay sets the value for the OplogReplay field. OplogReplay is for internal
// replication use only and should not be set.
//
// Deprecated: This option has been deprecated in MongoDB version 4.4 and will be ignored by
// the server if it is set.
func (f *FindOptionsBuilder) SetOplogReplay(b bool) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.OplogReplay = &b
return nil
})
return f
}
// SetProjection sets the value for the Projection field. Projection is a document describing
// which fields will be included in the documents returned by the Find operation. The
// default value is nil, which means all fields will be included.
func (f *FindOptionsBuilder) SetProjection(projection any) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Projection = projection
return nil
})
return f
}
// SetReturnKey sets the value for the ReturnKey field. ReturnKey specifies whether the
// documents returned by the Find operation will only contain fields corresponding to the
// index used. The default value is false.
func (f *FindOptionsBuilder) SetReturnKey(b bool) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.ReturnKey = &b
return nil
})
return f
}
// SetShowRecordID sets the value for the ShowRecordID field. ShowRecordID specifies whether
// a $recordId field with a record identifier will be included in the documents returned by
// the Find operation. The default value is false.
func (f *FindOptionsBuilder) SetShowRecordID(b bool) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.ShowRecordID = &b
return nil
})
return f
}
// SetSkip sets the value for the Skip field. Skip is the number of documents to skip before
// adding documents to the result. The default value is 0.
func (f *FindOptionsBuilder) SetSkip(i int64) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Skip = &i
return nil
})
return f
}
// SetSort sets the value for the Sort field. Sort is a document specifying the order in which
// documents should be returned. The sort parameter is evaluated sequentially, so the driver will
// return an error if it is a multi-key map (which is unordeded). The default value is nil.
func (f *FindOptionsBuilder) SetSort(sort any) *FindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOptions) error {
opts.Sort = sort
return nil
})
return f
}
// FindOneOptions represents arguments that can be used to configure a FindOne
// operation.
//
// See corresponding setter methods for documentation.
type FindOneOptions struct {
AllowPartialResults *bool
Collation *Collation
Comment any
Hint any
Max any
Min any
OplogReplay *bool
Projection any
ReturnKey *bool
ShowRecordID *bool
Skip *int64
Sort any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// FindOneOptionsBuilder represents functional options that configure an
// FindOneopts.
type FindOneOptionsBuilder struct {
Opts []func(*FindOneOptions) error
}
// FindOne creates a new FindOneOptions instance.
func FindOne() *FindOneOptionsBuilder {
return &FindOneOptionsBuilder{}
}
// List returns a list of FindOneOptions setter functions.
func (f *FindOneOptionsBuilder) List() []func(*FindOneOptions) error {
return f.Opts
}
// SetAllowPartialResults sets the value for the AllowPartialResults field. If true, an operation
// on a sharded cluster can return partial results if some shards are down rather than returning
// an error. The default value is false.
func (f *FindOneOptionsBuilder) SetAllowPartialResults(b bool) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.AllowPartialResults = &b
return nil
})
return f
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (f *FindOneOptionsBuilder) SetCollation(collation *Collation) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Collation = collation
return nil
})
return f
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default is nil, which means that no comment will be included in the logs.
func (f *FindOneOptionsBuilder) SetComment(comment any) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Comment = &comment
return nil
})
return f
}
// SetHint sets the value for the Hint field. Specifies the index to use for the aggregation.
// This should either be the index name as a string or the index specification as a document.
// The driver will return an error if the hint parameter is a multi-key map. The default value
// is nil, which means that no hint will be sent.
func (f *FindOneOptionsBuilder) SetHint(hint any) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Hint = hint
return nil
})
return f
}
// SetMax sets the value for the Max field. Sets a document specifying the exclusive upper bound
// for a specific index. The default value is nil, which means that there is no maximum value.
func (f *FindOneOptionsBuilder) SetMax(max any) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Max = max
return nil
})
return f
}
// SetMin sets the value for the Min field. Sets a document specifying the inclusive lower bound
// for a specific index. The default value is 0, which means that there is no minimum value.
func (f *FindOneOptionsBuilder) SetMin(min any) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Min = min
return nil
})
return f
}
// SetOplogReplay sets the value for the OplogReplay field. OplogReplay is for internal
// replication use only and should not be set.
//
// Deprecated: This option has been deprecated in MongoDB version 4.4 and will be ignored by
// the server if it is set.
func (f *FindOneOptionsBuilder) SetOplogReplay(b bool) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.OplogReplay = &b
return nil
})
return f
}
// SetProjection sets the value for the Projection field. Sets a document describing which fields
// will be included in the document returned by the operation. The default value is nil, which
// means all fields will be included.
func (f *FindOneOptionsBuilder) SetProjection(projection any) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Projection = projection
return nil
})
return f
}
// SetReturnKey sets the value for the ReturnKey field. If true, the document returned by the
// operation will only contain fields corresponding to the index used. The default value
// is false.
func (f *FindOneOptionsBuilder) SetReturnKey(b bool) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.ReturnKey = &b
return nil
})
return f
}
// SetShowRecordID sets the value for the ShowRecordID field. If true, a $recordId field with
// a record identifier will be included in the document returned by the operation. The default
// value is false.
func (f *FindOneOptionsBuilder) SetShowRecordID(b bool) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.ShowRecordID = &b
return nil
})
return f
}
// SetSkip sets the value for the Skip field. Specifies the number of documents to skip before
// selecting the document to be returned. The default value is 0.
func (f *FindOneOptionsBuilder) SetSkip(i int64) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Skip = &i
return nil
})
return f
}
// SetSort sets the value for the Sort field. Sets a document specifying the sort order to
// apply to the query. The first document in the sorted order will be returned. The sort
// parameter is evaluated sequentially, so the driver will return an error if it is a multi-
// key map (which is unordeded). The default value is nil.
func (f *FindOneOptionsBuilder) SetSort(sort any) *FindOneOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneOptions) error {
opts.Sort = sort
return nil
})
return f
}
// FindOneAndReplaceOptions represents arguments that can be used to configure a
// FindOneAndReplace instance.
//
// See corresponding setter methods for documentation.
type FindOneAndReplaceOptions struct {
BypassDocumentValidation *bool
Collation *Collation
Comment any
Projection any
ReturnDocument *ReturnDocument
Sort any
Upsert *bool
Hint any
Let any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// FindOneAndReplaceOptionsBuilder contains options to perform a findAndModify
// operation. Each option can be set through setter functions. See documentation
// for each setter function for an explanation of the option.
type FindOneAndReplaceOptionsBuilder struct {
Opts []func(*FindOneAndReplaceOptions) error
}
// FindOneAndReplace creates a new FindOneAndReplaceOptions instance.
func FindOneAndReplace() *FindOneAndReplaceOptionsBuilder {
return &FindOneAndReplaceOptionsBuilder{}
}
// List returns a list of FindOneAndReplaceOptions setter functions.
func (f *FindOneAndReplaceOptionsBuilder) List() []func(*FindOneAndReplaceOptions) error {
return f.Opts
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes
// executed as part of the operation will opt out of document-level validation on the server. The
// default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more
// information about document validation.
func (f *FindOneAndReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return f
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (f *FindOneAndReplaceOptionsBuilder) SetCollation(collation *Collation) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.Collation = collation
return nil
})
return f
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (f *FindOneAndReplaceOptionsBuilder) SetComment(comment any) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.Comment = comment
return nil
})
return f
}
// SetProjection sets the value for the Projection field. Sets a document describing which fields
// will be included in the document returned by the operation. The default value is nil, which
// means all fields will be included.
func (f *FindOneAndReplaceOptionsBuilder) SetProjection(projection any) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.Projection = projection
return nil
})
return f
}
// SetReturnDocument sets the value for the ReturnDocument field. Specifies whether the original
// or replaced document should be returned by the operation. The default value is Before, which
// means the original document will be returned from before the replacement is performed.
func (f *FindOneAndReplaceOptionsBuilder) SetReturnDocument(rd ReturnDocument) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.ReturnDocument = &rd
return nil
})
return f
}
// SetSort sets the value for the Sort field. Sets a document specifying which document should
// be replaced if the filter used by the operation matches multiple documents in the collection.
// If set, the first document in the sorted order will be replaced. The sort parameter is evaluated
// sequentially, so the driver will return an error if it is a multi-key map (which is unordeded).
// The default value is nil.
func (f *FindOneAndReplaceOptionsBuilder) SetSort(sort any) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.Sort = sort
return nil
})
return f
}
// SetUpsert sets the value for the Upsert field. If true, a new document will be inserted if
// the filter does not match any documents in the collection. The default value is false.
func (f *FindOneAndReplaceOptionsBuilder) SetUpsert(b bool) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.Upsert = &b
return nil
})
return f
}
// SetHint sets the value for the Hint field. Specifies the index to use for the operation.
// This should either be the index name as a string or the index specification as a document.
// This option is only valid for MongoDB versions >= 4.4. MongoDB version 4.2 will report an
// error if this option is specified. For server versions < 4.2, the driver will return an
// error if this option is specified. The driver will return an error if this option is used
// with during an unacknowledged write operation. The driver will return an error if the
// hint parameter is a multi-key map. The default value is nil, which means that no hint
// will be sent.
func (f *FindOneAndReplaceOptionsBuilder) SetHint(hint any) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.Hint = hint
return nil
})
return f
}
// SetLet sets the value for the Let field. Specifies parameters for the find one and
// replace expression. This option is only valid for MongoDB versions >= 5.0. Older
// servers will report an error for using this option. This must be a document mapping
// parameter names to values. Values must be constant or closed expressions that do not
// reference document fields. Parameters can then be accessed as variables in an
// aggregate expression context (e.g. "$$var").
func (f *FindOneAndReplaceOptionsBuilder) SetLet(let any) *FindOneAndReplaceOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error {
opts.Let = let
return nil
})
return f
}
// FindOneAndUpdateOptions represents arguments that can be used to configure a
// FindOneAndUpdate options.
//
// See corresponding setter methods for documentation.
type FindOneAndUpdateOptions struct {
ArrayFilters []any
BypassDocumentValidation *bool
Collation *Collation
Comment any
Projection any
ReturnDocument *ReturnDocument
Sort any
Upsert *bool
Hint any
Let any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// FindOneAndUpdateOptionsBuilder contains options to configure a
// findOneAndUpdate operation. Each option can be set through setter functions.
// See documentation for each setter function for an explanation of the option.
type FindOneAndUpdateOptionsBuilder struct {
Opts []func(*FindOneAndUpdateOptions) error
}
// FindOneAndUpdate creates a new FindOneAndUpdateOptions instance.
func FindOneAndUpdate() *FindOneAndUpdateOptionsBuilder {
return &FindOneAndUpdateOptionsBuilder{}
}
// List returns a list of FindOneAndUpdateOptions setter functions.
func (f *FindOneAndUpdateOptionsBuilder) List() []func(*FindOneAndUpdateOptions) error {
return f.Opts
}
// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a
// set of filters specifying to which array elements an update should apply. The
// default value is nil, which means the update will apply to all array
// elements.
func (f *FindOneAndUpdateOptionsBuilder) SetArrayFilters(filters []any) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.ArrayFilters = filters
return nil
})
return f
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true,
// writes executed as part of the operation will opt out of document-level validation on the server.
// The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/
// for more information about document validation.
func (f *FindOneAndUpdateOptionsBuilder) SetBypassDocumentValidation(b bool) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return f
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (f *FindOneAndUpdateOptionsBuilder) SetCollation(collation *Collation) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.Collation = collation
return nil
})
return f
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (f *FindOneAndUpdateOptionsBuilder) SetComment(comment any) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.Comment = comment
return nil
})
return f
}
// SetProjection sets the value for the Projection field. Sets a document describing which fields
// will be included in the document returned by the operation. The default value is nil, which
// means all fields will be included.
func (f *FindOneAndUpdateOptionsBuilder) SetProjection(projection any) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.Projection = projection
return nil
})
return f
}
// SetReturnDocument sets the value for the ReturnDocument field. Specifies whether the original
// or replaced document should be returned by the operation. The default value is Before, which
// means the original document will be returned before the replacement is performed.
func (f *FindOneAndUpdateOptionsBuilder) SetReturnDocument(rd ReturnDocument) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.ReturnDocument = &rd
return nil
})
return f
}
// SetSort sets the value for the Sort field. Sets a document specifying which document should
// be updated if the filter used by the operation matches multiple documents in the collection.
// If set, the first document in the sorted order will be updated. The sort parameter is evaluated
// sequentially, so the driver will return an error if it is a multi-key map (which is unordeded).
// The default value is nil.
func (f *FindOneAndUpdateOptionsBuilder) SetSort(sort any) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.Sort = sort
return nil
})
return f
}
// SetUpsert sets the value for the Upsert field. If true, a new document will be inserted if
// the filter does not match any documents in the collection. The default value is false.
func (f *FindOneAndUpdateOptionsBuilder) SetUpsert(b bool) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.Upsert = &b
return nil
})
return f
}
// SetHint sets the value for the Hint field. Specifies the index to use for the operation.
// This should either be the index name as a string or the index specification as a document.
// This option is only valid for MongoDB versions >= 4.4. MongoDB version 4.2 will report an
// error if this option is specified. For server versions < 4.2, the driver will return an
// error if this option is specified. The driver will return an error if this option is used
// with during an unacknowledged write operation. The driver will return an error if the
// hint parameter is a multi-key map. The default value is nil, which means that no hint
// will be sent.
func (f *FindOneAndUpdateOptionsBuilder) SetHint(hint any) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.Hint = hint
return nil
})
return f
}
// SetLet sets the value for the Let field. Specifies parameters for the find one and update
// expression. This option is only valid for MongoDB versions >= 5.0. Older servers will
// report an error for using this option. This must be a document mapping parameter names
// to values. Values must be constant or closed expressions that do not reference document
// fields. Parameters can then be accessed as variables in an aggregate expression context
// (e.g. "$$var").
func (f *FindOneAndUpdateOptionsBuilder) SetLet(let any) *FindOneAndUpdateOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error {
opts.Let = let
return nil
})
return f
}
// FindOneAndDeleteOptions represents arguments that can be used to configure a
// FindOneAndDelete operation.
//
// See corresponding setter methods for documentation.
type FindOneAndDeleteOptions struct {
Collation *Collation
Comment any
Projection any
Sort any
Hint any
Let any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// FindOneAndDeleteOptionsBuilder contains options to configure delete
// operations. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type FindOneAndDeleteOptionsBuilder struct {
Opts []func(*FindOneAndDeleteOptions) error
}
// FindOneAndDelete creates a new FindOneAndDeleteOptions instance.
func FindOneAndDelete() *FindOneAndDeleteOptionsBuilder {
return &FindOneAndDeleteOptionsBuilder{}
}
// List returns a list of FindOneAndDeleteOptions setter functions.
func (f *FindOneAndDeleteOptionsBuilder) List() []func(*FindOneAndDeleteOptions) error {
return f.Opts
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (f *FindOneAndDeleteOptionsBuilder) SetCollation(collation *Collation) *FindOneAndDeleteOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error {
opts.Collation = collation
return nil
})
return f
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (f *FindOneAndDeleteOptionsBuilder) SetComment(comment any) *FindOneAndDeleteOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error {
opts.Comment = comment
return nil
})
return f
}
// SetProjection sets the value for the Projection field. Sets a document describing which fields
// will be included in the document returned by the operation. The default value is nil, which
// means all fields will be included.
func (f *FindOneAndDeleteOptionsBuilder) SetProjection(projection any) *FindOneAndDeleteOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error {
opts.Projection = projection
return nil
})
return f
}
// SetSort sets the value for the Sort field. Sets a document specifying which document should
// be replaced if the filter used by the operation matches multiple documents in the collection.
// If set, the first document in the sorted order will be deleted. The sort parameter is evaluated
// sequentially, so the driver will return an error if it is a multi-key map (which is unordeded).
// The default value is nil.
func (f *FindOneAndDeleteOptionsBuilder) SetSort(sort any) *FindOneAndDeleteOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error {
opts.Sort = sort
return nil
})
return f
}
// SetHint sets the value for the Hint field. Specifies the index to use for the operation.
// This should either be the index name as a string or the index specification as a document.
// This option is only valid for MongoDB versions >= 4.4. MongoDB version 4.2 will report an
// error if this option is specified. For server versions < 4.2, the driver will return an
// error if this option is specified. The driver will return an error if this option is used
// with during an unacknowledged write operation. The driver will return an error if the hint
// parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
func (f *FindOneAndDeleteOptionsBuilder) SetHint(hint any) *FindOneAndDeleteOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error {
opts.Hint = hint
return nil
})
return f
}
// SetLet sets the value for the Let field. Specifies parameters for the find one and delete
// expression. This option is only valid for MongoDB versions >= 5.0. Older servers will
// report an error for using this option. This must be a document mapping parameter names to
// values. Values must be constant or closed expressions that do not reference document fields.
// Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var").
func (f *FindOneAndDeleteOptionsBuilder) SetLet(let any) *FindOneAndDeleteOptionsBuilder {
f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error {
opts.Let = let
return nil
})
return f
}

View File

@@ -0,0 +1,342 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)
// DefaultName is the default name for a GridFS bucket.
var DefaultName = "fs"
// DefaultChunkSize is the default size of each file chunk in bytes (255 KiB).
var DefaultChunkSize int32 = 255 * 1024
// DefaultRevision is the default revision number for a download by name operation.
var DefaultRevision int32 = -1
// BucketOptions represents arguments that can be used to configure GridFS
// bucket.
//
// See corresponding setter methods for documentation.
type BucketOptions struct {
Name *string
ChunkSizeBytes *int32
WriteConcern *writeconcern.WriteConcern
ReadConcern *readconcern.ReadConcern
ReadPreference *readpref.ReadPref
}
// BucketOptionsBuilder contains options to configure a gridfs bucket. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type BucketOptionsBuilder struct {
Opts []func(*BucketOptions) error
}
// GridFSBucket creates a new BucketOptions instance.
func GridFSBucket() *BucketOptionsBuilder {
bo := &BucketOptionsBuilder{}
bo.SetName(DefaultName).SetChunkSizeBytes(DefaultChunkSize)
return bo
}
// List returns a list of CountOptions setter functions.
func (b *BucketOptionsBuilder) List() []func(*BucketOptions) error {
return b.Opts
}
// SetName sets the value for the Name field. Specifies the name of the bucket.
// The default value is "fs".
func (b *BucketOptionsBuilder) SetName(name string) *BucketOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BucketOptions) error {
opts.Name = &name
return nil
})
return b
}
// SetChunkSizeBytes sets the value for the ChunkSize field. Specifies the number
// of bytes in each chunk in the bucket. The default value is 255 KiB.
func (b *BucketOptionsBuilder) SetChunkSizeBytes(i int32) *BucketOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BucketOptions) error {
opts.ChunkSizeBytes = &i
return nil
})
return b
}
// SetWriteConcern sets the value for the WriteConcern field. Specifies the write
// concern for the bucket. The default value is the write concern of the database
// from which the bucket is created.
func (b *BucketOptionsBuilder) SetWriteConcern(wc *writeconcern.WriteConcern) *BucketOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BucketOptions) error {
opts.WriteConcern = wc
return nil
})
return b
}
// SetReadConcern sets the value for the ReadConcern field. Specifies the read
// concern for the bucket. The default value is the read concern of the database
// from which the bucket is created.
func (b *BucketOptionsBuilder) SetReadConcern(rc *readconcern.ReadConcern) *BucketOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BucketOptions) error {
opts.ReadConcern = rc
return nil
})
return b
}
// SetReadPreference sets the value for the ReadPreference field. Specifies the
// read preference for the bucket. The default value is the read preference of
// the database from which the bucket is created.
func (b *BucketOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *BucketOptionsBuilder {
b.Opts = append(b.Opts, func(opts *BucketOptions) error {
opts.ReadPreference = rp
return nil
})
return b
}
// GridFSUploadOptions represents arguments that can be used to configure a GridFS
// upload operation.
//
// See corresponding setter methods for documentation.
type GridFSUploadOptions struct {
ChunkSizeBytes *int32
Metadata any
Registry *bson.Registry
}
// GridFSUploadOptionsBuilder contains options to configure a GridFS Upload.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type GridFSUploadOptionsBuilder struct {
Opts []func(*GridFSUploadOptions) error
}
// GridFSUpload creates a new GridFSUploadOptions instance.
func GridFSUpload() *GridFSUploadOptionsBuilder {
opts := &GridFSUploadOptionsBuilder{}
opts.SetRegistry(defaultRegistry)
return opts
}
// List returns a list of GridFSUploadOptions setter functions.
func (u *GridFSUploadOptionsBuilder) List() []func(*GridFSUploadOptions) error {
return u.Opts
}
// SetChunkSizeBytes sets the value for the ChunkSize field. Specifies the number of
// bytes in each chunk in the bucket. The default value is DefaultChunkSize (255 KiB).
func (u *GridFSUploadOptionsBuilder) SetChunkSizeBytes(i int32) *GridFSUploadOptionsBuilder {
u.Opts = append(u.Opts, func(opts *GridFSUploadOptions) error {
opts.ChunkSizeBytes = &i
return nil
})
return u
}
// SetMetadata sets the value for the Metadata field. Specifies additional application data
// that will be stored in the "metadata" field of the document in the files collection.
// The default value is nil, which means that the document in the files collection will
// not contain a "metadata" field.
func (u *GridFSUploadOptionsBuilder) SetMetadata(doc any) *GridFSUploadOptionsBuilder {
u.Opts = append(u.Opts, func(opts *GridFSUploadOptions) error {
opts.Metadata = doc
return nil
})
return u
}
// SetRegistry sets the bson codec registry for the Registry field. Specifies the BSON
// registry to use for converting filters to BSON documents. The default value is
// bson.NewRegistry().
func (u *GridFSUploadOptionsBuilder) SetRegistry(registry *bson.Registry) *GridFSUploadOptionsBuilder {
u.Opts = append(u.Opts, func(opts *GridFSUploadOptions) error {
opts.Registry = registry
return nil
})
return u
}
// GridFSNameOptions represents arguments that can be used to configure a GridFS
// DownloadByName operation.
//
// See corresponding setter methods for documentation.
type GridFSNameOptions struct {
Revision *int32
}
// GridFSNameOptionsBuilder contains options to configure a GridFS name. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type GridFSNameOptionsBuilder struct {
Opts []func(*GridFSNameOptions) error
}
// GridFSName creates a new GridFSNameOptions instance.
func GridFSName() *GridFSNameOptionsBuilder {
return &GridFSNameOptionsBuilder{}
}
// List returns a list of GridFSNameOptions setter functions.
func (n *GridFSNameOptionsBuilder) List() []func(*GridFSNameOptions) error {
return n.Opts
}
// SetRevision sets the value for the Revision field. Specifies the revision
// of the file to retrieve. Revision numbers are defined as follows:
//
// * 0 = the original stored file
// * 1 = the first revision
// * 2 = the second revision
// * etc..
// * -2 = the second most recent revision
// * -1 = the most recent revision.
//
// The default value is -1
func (n *GridFSNameOptionsBuilder) SetRevision(r int32) *GridFSNameOptionsBuilder {
n.Opts = append(n.Opts, func(opts *GridFSNameOptions) error {
opts.Revision = &r
return nil
})
return n
}
// GridFSFindOptions represents arguments that can be used to configure a GridFS
// Find operation.
//
// See corresponding setter methods for documentation.
type GridFSFindOptions struct {
AllowDiskUse *bool
BatchSize *int32
Limit *int32
NoCursorTimeout *bool
Skip *int32
Sort any
}
// GridFSFindOptionsBuilder contains options to configure find operations. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type GridFSFindOptionsBuilder struct {
Opts []func(*GridFSFindOptions) error
}
// GridFSFind creates a new GridFSFindOptions instance.
func GridFSFind() *GridFSFindOptionsBuilder {
return &GridFSFindOptionsBuilder{}
}
// List returns a list of GridFSFindOptions setter functions.
func (f *GridFSFindOptionsBuilder) List() []func(*GridFSFindOptions) error {
return f.Opts
}
// SetAllowDiskUse sets the value for the AllowDiskUse field. If true, the server can
// write temporary data to disk while executing the find operation. The default value
// is false. This option is only valid for MongoDB versions >= 4.4. For previous server
// versions, the server will return an error if this option is used.
func (f *GridFSFindOptionsBuilder) SetAllowDiskUse(b bool) *GridFSFindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error {
opts.AllowDiskUse = &b
return nil
})
return f
}
// SetBatchSize sets the value for the BatchSize field. Specifies the maximum number
// of documents to be included in each batch returned by the server.
func (f *GridFSFindOptionsBuilder) SetBatchSize(i int32) *GridFSFindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error {
opts.BatchSize = &i
return nil
})
return f
}
// SetLimit sets the value for the Limit field. Specifies the maximum number of
// documents to return. The default value is 0, which means that all documents
// matching the filter will be returned. A negative limit specifies that the
// resulting documents should be returned in a single batch. The default value is 0.
func (f *GridFSFindOptionsBuilder) SetLimit(i int32) *GridFSFindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error {
opts.Limit = &i
return nil
})
return f
}
// SetNoCursorTimeout sets the value for the NoCursorTimeout field. If true, the
// cursor created by the operation will not timeout after a period of inactivity.
// The default value is false.
func (f *GridFSFindOptionsBuilder) SetNoCursorTimeout(b bool) *GridFSFindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error {
opts.NoCursorTimeout = &b
return nil
})
return f
}
// SetSkip sets the value for the Skip field. Specifies the number of documents
// to skip before adding documents to the result. The default value is 0.
func (f *GridFSFindOptionsBuilder) SetSkip(i int32) *GridFSFindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error {
opts.Skip = &i
return nil
})
return f
}
// SetSort sets the value for the Sort field. Sets a document specifying the order
// in which documents should be returned. The sort parameter is evaluated sequentially,
// so the driver will return an error if it is a multi-key map (which is unordeded).
// The default value is nil.
func (f *GridFSFindOptionsBuilder) SetSort(sort any) *GridFSFindOptionsBuilder {
f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error {
opts.Sort = sort
return nil
})
return f
}

View File

@@ -0,0 +1,486 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// CreateIndexesOptions represents arguments that can be used to configure
// IndexView.CreateOne and IndexView.CreateMany operations.
//
// See corresponding setter methods for documentation.
type CreateIndexesOptions struct {
CommitQuorum any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// CreateIndexesOptionsBuilder contains options to create indexes. Each option
// can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
//
// See corresponding setter methods for documentation.
type CreateIndexesOptionsBuilder struct {
Opts []func(*CreateIndexesOptions) error
}
// CreateIndexes creates a new CreateIndexesOptions instance.
func CreateIndexes() *CreateIndexesOptionsBuilder {
return &CreateIndexesOptionsBuilder{}
}
// List returns a list of CreateIndexesOptions setter functions.
func (c *CreateIndexesOptionsBuilder) List() []func(*CreateIndexesOptions) error {
return c.Opts
}
// SetCommitQuorumInt sets the value for the CommitQuorum field as an int32.
// Specifies the number of data-bearing members of a replica set, including the primary,
// that must complete the index builds successfully before the primary marks the indexes
// as ready.
//
// Semantics for int: the number of members that must complete the build.
//
// This option is only available on MongoDB versions >= 4.4. A client-side error will
// be returned if the option is specified for MongoDB versions <= 4.2. The default
// value is nil, meaning that the server-side default will be used. See
// dochub.mongodb.org/core/index-commit-quorum for more information.
func (c *CreateIndexesOptionsBuilder) SetCommitQuorumInt(quorum int32) *CreateIndexesOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateIndexesOptions) error {
opts.CommitQuorum = quorum
return nil
})
return c
}
// SetCommitQuorumString sets the value for the CommitQuorum field as a string.
// Specifies the number of data-bearing members of a replica set, including the primary,
// that must complete the index builds successfully before the primary marks the indexes
// as ready.
//
// Semantics for String: specifies a tag. All members with that tag must complete the build.
//
// This option is only available on MongoDB versions >= 4.4. A client-side error will
// be returned if the option is specified for MongoDB versions <= 4.2. The default
// value is nil, meaning that the server-side default will be used. See
// dochub.mongodb.org/core/index-commit-quorum for more information.
func (c *CreateIndexesOptionsBuilder) SetCommitQuorumString(quorum string) *CreateIndexesOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateIndexesOptions) error {
opts.CommitQuorum = quorum
return nil
})
return c
}
// SetCommitQuorumMajority sets the value for the CommitQuorum to special "majority" value.
// Specifies the number of data-bearing members of a replica set, including the primary,
// that must complete the index builds successfully before the primary marks the indexes
// as ready.
//
// Semantics for "majority": A special value to indicate that more than half the nodes
// must complete the build.
//
// This option is only available on MongoDB versions >= 4.4. A client-side error will
// be returned if the option is specified for MongoDB versions <= 4.2. The default
// value is nil, meaning that the server-side default will be used. See
// dochub.mongodb.org/core/index-commit-quorum for more information.
func (c *CreateIndexesOptionsBuilder) SetCommitQuorumMajority() *CreateIndexesOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateIndexesOptions) error {
opts.CommitQuorum = "majority"
return nil
})
return c
}
// SetCommitQuorumVotingMembers sets the value for the CommitQuorum to special "votingMembers" value.
// Specifies the number of data-bearing members of a replica set, including the primary,
// that must complete the index builds successfully before the primary marks the indexes
// as ready.
//
// Semantics for "votingMembers": A special value to indicate that all voting data-bearing
// nodes must complete.
//
// This option is only available on MongoDB versions >= 4.4. A client-side error will
// be returned if the option is specified for MongoDB versions <= 4.2. The default
// value is nil, meaning that the server-side default will be used. See
// dochub.mongodb.org/core/index-commit-quorum for more information.
func (c *CreateIndexesOptionsBuilder) SetCommitQuorumVotingMembers() *CreateIndexesOptionsBuilder {
c.Opts = append(c.Opts, func(opts *CreateIndexesOptions) error {
opts.CommitQuorum = "votingMembers"
return nil
})
return c
}
// DropIndexesOptions represents arguments that can be used to configure
// IndexView.DropOne and IndexView.DropAll operations.
type DropIndexesOptions struct {
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// DropIndexesOptionsBuilder contains options to configure dropping indexes.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type DropIndexesOptionsBuilder struct {
Opts []func(*DropIndexesOptions) error
}
// DropIndexes creates a new DropIndexesOptions instance.
func DropIndexes() *DropIndexesOptionsBuilder {
return &DropIndexesOptionsBuilder{}
}
// List returns a list of DropIndexesOptions setter functions.
func (d *DropIndexesOptionsBuilder) List() []func(*DropIndexesOptions) error {
return d.Opts
}
// ListIndexesOptions represents arguments that can be used to configure an
// IndexView.List operation.
//
// See corresponding setter methods for documentation.
type ListIndexesOptions struct {
BatchSize *int32
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// ListIndexesOptionsBuilder contains options to configure count operations. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type ListIndexesOptionsBuilder struct {
Opts []func(*ListIndexesOptions) error
}
// ListIndexes creates a new ListIndexesOptions instance.
func ListIndexes() *ListIndexesOptionsBuilder {
return &ListIndexesOptionsBuilder{}
}
// List returns a list of CountOptions setter functions.
func (l *ListIndexesOptionsBuilder) List() []func(*ListIndexesOptions) error {
return l.Opts
}
// SetBatchSize sets the value for the BatchSize field. Specifies the maximum number
// of documents to be included in each batch returned by the server.
func (l *ListIndexesOptionsBuilder) SetBatchSize(i int32) *ListIndexesOptionsBuilder {
l.Opts = append(l.Opts, func(opts *ListIndexesOptions) error {
opts.BatchSize = &i
return nil
})
return l
}
// IndexOptions represents arguments that can be used to configure a new index
// created through the IndexView.CreateOne or IndexView.CreateMany operations.
//
// See corresponding setter methods for documentation.
type IndexOptions struct {
ExpireAfterSeconds *int32
Name *string
Sparse *bool
StorageEngine any
Unique *bool
Version *int32
DefaultLanguage *string
LanguageOverride *string
TextVersion *int32
Weights any
SphereVersion *int32
Bits *int32
Max *float64
Min *float64
BucketSize *int32
PartialFilterExpression any
Collation *Collation
WildcardProjection any
Hidden *bool
}
// IndexOptionsBuilder contains options to configure index operations. Each option
// can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type IndexOptionsBuilder struct {
Opts []func(*IndexOptions) error
}
// Index creates a new IndexOptions instance.
func Index() *IndexOptionsBuilder {
return &IndexOptionsBuilder{}
}
// List returns a list of IndexOptions setter functions.
func (i *IndexOptionsBuilder) List() []func(*IndexOptions) error {
return i.Opts
}
// SetExpireAfterSeconds sets value for the ExpireAfterSeconds field. Specifies the length
// of time, in seconds, for documents to remain in the collection. The default value is 0,
// which means that documents will remain in the collection until they're explicitly
// deleted or the collection is dropped.
func (i *IndexOptionsBuilder) SetExpireAfterSeconds(seconds int32) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.ExpireAfterSeconds = &seconds
return nil
})
return i
}
// SetName sets the value for the Name field. Specifies the name of the index. The default
// value is "[field1]_[direction1]_[field2]_[direction2]...". For example, an index with
// the specification {name: 1, age: -1} will be named "name_1_age_-1".
func (i *IndexOptionsBuilder) SetName(name string) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Name = &name
return nil
})
return i
}
// SetSparse sets the value of the Sparse field. If true, the index will only reference
// documents that contain the fields specified in the index. The default is false.
func (i *IndexOptionsBuilder) SetSparse(sparse bool) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Sparse = &sparse
return nil
})
return i
}
// SetStorageEngine sets the value for the StorageEngine field. Specifies the
// storage engine to use for the index. The value must be a document in the form
// {<storage engine name>: <options>}. The default value is nil, which means that
// the default storage engine will be used.
func (i *IndexOptionsBuilder) SetStorageEngine(engine any) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.StorageEngine = engine
return nil
})
return i
}
// SetUnique sets the value for the Unique field. If true, the collection will not
// accept insertion or update of documents where the index key value matches an
// existing value in the index. The default is false.
func (i *IndexOptionsBuilder) SetUnique(unique bool) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Unique = &unique
return nil
})
return i
}
// SetVersion sets the value for the Version field. Specifies the index version
// number, either 0 or 1.
func (i *IndexOptionsBuilder) SetVersion(version int32) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Version = &version
return nil
})
return i
}
// SetDefaultLanguage sets the value for the DefaultLanguage field. Specifies the
// language that determines the list of stop words and the rules for the stemmer
// and tokenizer. This option is only applicable for text indexes and is ignored for
// other index types. The default value is "english".
func (i *IndexOptionsBuilder) SetDefaultLanguage(language string) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.DefaultLanguage = &language
return nil
})
return i
}
// SetLanguageOverride sets the value of the LanguageOverride field. Specifies the name
// of the field in the collection's documents that contains the override language for the
// document. This option is only applicable for text indexes and is ignored for other index
// types. The default value is the value of the DefaultLanguage option.
func (i *IndexOptionsBuilder) SetLanguageOverride(override string) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.LanguageOverride = &override
return nil
})
return i
}
// SetTextVersion sets the value for the TextVersion field. Specifies the index version number
// for a text index. See https://www.mongodb.com/docs/manual/core/index-text/#text-versions
// for information about different version numbers.
func (i *IndexOptionsBuilder) SetTextVersion(version int32) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.TextVersion = &version
return nil
})
return i
}
// SetWeights sets the value for the Weights field. Sets a document that contains field
// and weight pairs. The weight is an integer ranging from 1 to 99,999, inclusive,
// indicating the significance of the field relative to the other indexed fields in
// terms of the score. This option is only applicable for text indexes and is ignored
// for other index types. The default value is nil, which means that every field will
// have a weight of 1.
func (i *IndexOptionsBuilder) SetWeights(weights any) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Weights = weights
return nil
})
return i
}
// SetSphereVersion sets the value for the SphereVersion field. Specifies the index version number
// for a 2D sphere index. See https://www.mongodb.com/docs/manual/core/2dsphere/#dsphere-v2 for
// information about different version numbers.
func (i *IndexOptionsBuilder) SetSphereVersion(version int32) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.SphereVersion = &version
return nil
})
return i
}
// SetBits sets the value for the Bits field. Specifies the precision of the stored geohash
// value of the location data. This option only applies to 2D indexes and is ignored for
// other index types. The value must be between 1 and 32, inclusive. The default value is 26.
func (i *IndexOptionsBuilder) SetBits(bits int32) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Bits = &bits
return nil
})
return i
}
// SetMax sets the value for the Max field. Specifies the upper inclusive boundary for
// longitude and latitude values. This option is only applicable to 2D indexes and
// is ignored for other index types. The default value is 180.0.
func (i *IndexOptionsBuilder) SetMax(max float64) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Max = &max
return nil
})
return i
}
// SetMin sets the value for the Min field. Specifies the lower inclusive boundary for
// longitude and latitude values. This option is only applicable to 2D indexes and
// is ignored for other index types. The default value is -180.0.
func (i *IndexOptionsBuilder) SetMin(min float64) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Min = &min
return nil
})
return i
}
// SetBucketSize sets the value for the BucketSize field. Specifies the number of units
// within which to group location values. Location values that are within BucketSize
// units of each other will be grouped in the same bucket. This option is only applicable
// to geoHaystack indexes and is ignored for other index types. The value must be greater
// than 0.
func (i *IndexOptionsBuilder) SetBucketSize(bucketSize int32) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.BucketSize = &bucketSize
return nil
})
return i
}
// SetPartialFilterExpression sets the value for the PartialFilterExpression field. Sets
// a document that defines which collection documents the index should reference.
func (i *IndexOptionsBuilder) SetPartialFilterExpression(expression any) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.PartialFilterExpression = expression
return nil
})
return i
}
// SetCollation sets the value for the Collation field. Specifies the collation to use for
// string comparisons for the index.
func (i *IndexOptionsBuilder) SetCollation(collation *Collation) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Collation = collation
return nil
})
return i
}
// SetWildcardProjection sets the value for the WildcardProjection field. Sets a document
// that defines the wildcard projection for the index.
func (i *IndexOptionsBuilder) SetWildcardProjection(wildcardProjection any) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.WildcardProjection = wildcardProjection
return nil
})
return i
}
// SetHidden sets the value for the Hidden field. If true, the index will exist on the
// target collection but will not be used by the query planner when executing operations.
// This option is only valid for MongoDB versions >= 4.4. The default value is false.
func (i *IndexOptionsBuilder) SetHidden(hidden bool) *IndexOptionsBuilder {
i.Opts = append(i.Opts, func(opts *IndexOptions) error {
opts.Hidden = &hidden
return nil
})
return i
}

View File

@@ -0,0 +1,133 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// InsertOneOptions represents arguments that can be used to configure an InsertOne
// operation.
//
// See corresponding setter methods for documentation.
type InsertOneOptions struct {
BypassDocumentValidation *bool
Comment any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// InsertOneOptionsBuilder represents functional options that configure an
// InsertOneopts.
type InsertOneOptionsBuilder struct {
Opts []func(*InsertOneOptions) error
}
// InsertOne creates a new InsertOneOptions instance.
func InsertOne() *InsertOneOptionsBuilder {
return &InsertOneOptionsBuilder{}
}
// List returns a list of InsertOneOptions setter functions.
func (ioo *InsertOneOptionsBuilder) List() []func(*InsertOneOptions) error {
return ioo.Opts
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true,
// writes executed as part of the operation will opt out of document-level validation on the
// server. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/
// for more information about document validation.
func (ioo *InsertOneOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertOneOptionsBuilder {
ioo.Opts = append(ioo.Opts, func(opts *InsertOneOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return ioo
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
func (ioo *InsertOneOptionsBuilder) SetComment(comment any) *InsertOneOptionsBuilder {
ioo.Opts = append(ioo.Opts, func(opts *InsertOneOptions) error {
opts.Comment = &comment
return nil
})
return ioo
}
// InsertManyOptions represents arguments that can be used to configure an
// InsertMany operation.
//
// See corresponding setter methods for documentation.
type InsertManyOptions struct {
BypassDocumentValidation *bool
Comment any
Ordered *bool
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// InsertManyOptionsBuilder contains options to configure insert operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type InsertManyOptionsBuilder struct {
Opts []func(*InsertManyOptions) error
}
// InsertMany creates a new InsertManyOptions instance.
func InsertMany() *InsertManyOptionsBuilder {
opts := &InsertManyOptionsBuilder{}
opts.SetOrdered(DefaultOrdered)
return opts
}
// List returns a list of InsertManyOptions setter functions.
func (imo *InsertManyOptionsBuilder) List() []func(*InsertManyOptions) error {
return imo.Opts
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true,
// writes executed as part of the operation will opt out of document-level validation on the
// server. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/
// for more information about document validation.
func (imo *InsertManyOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertManyOptionsBuilder {
imo.Opts = append(imo.Opts, func(opts *InsertManyOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return imo
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (imo *InsertManyOptionsBuilder) SetComment(comment any) *InsertManyOptionsBuilder {
imo.Opts = append(imo.Opts, func(opts *InsertManyOptions) error {
opts.Comment = comment
return nil
})
return imo
}
// SetOrdered sets the value for the Ordered field. If true, no writes will be executed after
// one fails. The default value is true.
func (imo *InsertManyOptionsBuilder) SetOrdered(b bool) *InsertManyOptionsBuilder {
imo.Opts = append(imo.Opts, func(opts *InsertManyOptions) error {
opts.Ordered = &b
return nil
})
return imo
}

View File

@@ -0,0 +1,77 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// ListCollectionsOptions represents arguments that can be used to configure a
// ListCollections operation.
//
// See corresponding setter methods for documentation.
type ListCollectionsOptions struct {
NameOnly *bool
BatchSize *int32
AuthorizedCollections *bool
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// ListCollectionsOptionsBuilder contains options to configure list collection
// operations. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type ListCollectionsOptionsBuilder struct {
Opts []func(*ListCollectionsOptions) error
}
// ListCollections creates a new ListCollectionsOptions instance.
func ListCollections() *ListCollectionsOptionsBuilder {
return &ListCollectionsOptionsBuilder{}
}
// List returns a list of CountOptions setter functions.
func (lc *ListCollectionsOptionsBuilder) List() []func(*ListCollectionsOptions) error {
return lc.Opts
}
// SetNameOnly sets the value for the NameOnly field. If true, each collection document will only
// contain a field for the collection name. The default value is false.
func (lc *ListCollectionsOptionsBuilder) SetNameOnly(b bool) *ListCollectionsOptionsBuilder {
lc.Opts = append(lc.Opts, func(opts *ListCollectionsOptions) error {
opts.NameOnly = &b
return nil
})
return lc
}
// SetBatchSize sets the value for the BatchSize field. Specifies the maximum number of documents
// to be included in each batch returned by the server.
func (lc *ListCollectionsOptionsBuilder) SetBatchSize(size int32) *ListCollectionsOptionsBuilder {
lc.Opts = append(lc.Opts, func(opts *ListCollectionsOptions) error {
opts.BatchSize = &size
return nil
})
return lc
}
// SetAuthorizedCollections sets the value for the AuthorizedCollections field. If true, and
// NameOnly is true, limits the documents returned to only contain collections the user is
// authorized to use. The default value is false.
func (lc *ListCollectionsOptionsBuilder) SetAuthorizedCollections(b bool) *ListCollectionsOptionsBuilder {
lc.Opts = append(lc.Opts, func(opts *ListCollectionsOptions) error {
opts.AuthorizedCollections = &b
return nil
})
return lc
}

View File

@@ -0,0 +1,54 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// ListDatabasesOptions represents arguments that can be used to configure a
// ListDatabases operation.
//
// See corresponding setter methods for documentation.
type ListDatabasesOptions struct {
NameOnly *bool
AuthorizedDatabases *bool
}
// ListDatabasesOptionsBuilder represents functional options that configure a
// ListDatabasesopts.
type ListDatabasesOptionsBuilder struct {
Opts []func(*ListDatabasesOptions) error
}
// ListDatabases creates a new ListDatabasesOptions instance.
func ListDatabases() *ListDatabasesOptionsBuilder {
return &ListDatabasesOptionsBuilder{}
}
// List returns a list of ListDatabasesOptions setter functions.
func (ld *ListDatabasesOptionsBuilder) List() []func(*ListDatabasesOptions) error {
return ld.Opts
}
// SetNameOnly sets the value for the NameOnly field. If true, only the Name field of the returned
// DatabaseSpecification objects will be populated. The default value is false.
func (ld *ListDatabasesOptionsBuilder) SetNameOnly(b bool) *ListDatabasesOptionsBuilder {
ld.Opts = append(ld.Opts, func(opts *ListDatabasesOptions) error {
opts.NameOnly = &b
return nil
})
return ld
}
// SetAuthorizedDatabases sets the value for the AuthorizedDatabases field. If true, only the
// databases which the user is authorized to see will be returned. For more information about the
// behavior of this option, see https://www.mongodb.com/docs/manual/reference/privilege-actions/#find.
// The default value is true.
func (ld *ListDatabasesOptionsBuilder) SetAuthorizedDatabases(b bool) *ListDatabasesOptionsBuilder {
ld.Opts = append(ld.Opts, func(opts *ListDatabasesOptions) error {
opts.AuthorizedDatabases = &b
return nil
})
return ld
}

View File

@@ -0,0 +1,13 @@
// Copyright (C) MongoDB, Inc. 2024-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// Lister is an interface that wraps a List method to return a
// slice of option setters.
type Lister[T any] interface {
List() []func(*T) error
}

View File

@@ -0,0 +1,115 @@
// Copyright (C) MongoDB, Inc. 2023-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/internal/logger"
)
// LogLevel is an enumeration representing the supported log severity levels.
type LogLevel int
const (
// LogLevelInfo enables logging of informational messages. These logs
// are high-level information about normal driver behavior.
LogLevelInfo LogLevel = LogLevel(logger.LevelInfo)
// LogLevelDebug enables logging of debug messages. These logs can be
// voluminous and are intended for detailed information that may be
// helpful when debugging an application.
LogLevelDebug LogLevel = LogLevel(logger.LevelDebug)
)
// LogComponent is an enumeration representing the "components" which can be
// logged against. A LogLevel can be configured on a per-component basis.
type LogComponent int
const (
// LogComponentAll enables logging for all components.
LogComponentAll LogComponent = LogComponent(logger.ComponentAll)
// LogComponentCommand enables command monitor logging.
LogComponentCommand LogComponent = LogComponent(logger.ComponentCommand)
// LogComponentTopology enables topology logging.
LogComponentTopology LogComponent = LogComponent(logger.ComponentTopology)
// LogComponentServerSelection enables server selection logging.
LogComponentServerSelection LogComponent = LogComponent(logger.ComponentServerSelection)
// LogComponentConnection enables connection services logging.
LogComponentConnection LogComponent = LogComponent(logger.ComponentConnection)
)
// LogSink is an interface that can be implemented to provide a custom sink for
// the driver's logs.
type LogSink interface {
// Info logs a non-error message with the given key/value pairs. This
// method will only be called if the provided level has been defined
// for a component in the LoggerOptions.
//
// Here are the following level mappings for V = "Verbosity":
//
// - V(0): off
// - V(1): informational
// - V(2): debugging
//
// This level mapping is taken from the go-logr/logr library
// specifications, specifically:
//
// "Level V(0) is the default, and logger.V(0).Info() has the same
// meaning as logger.Info()."
Info(level int, message string, keysAndValues ...any)
// Error logs an error message with the given key/value pairs
Error(err error, message string, keysAndValues ...any)
}
// LoggerOptions represent arguments used to configure Logging in the Go Driver.
//
// See corresponding setter methods for documentation.
type LoggerOptions struct {
ComponentLevels map[LogComponent]LogLevel
Sink LogSink
MaxDocumentLength uint
}
// Logger creates a new LoggerOptions instance.
func Logger() *LoggerOptions {
return &LoggerOptions{}
}
// SetComponentLevel sets the LogLevel value for a LogComponent. ComponentLevels is a map of
// LogComponent to LogLevel. The LogLevel for a given LogComponent will be used to determine
// if a log message should be logged.
func (opts *LoggerOptions) SetComponentLevel(component LogComponent, level LogLevel) *LoggerOptions {
if opts.ComponentLevels == nil {
opts.ComponentLevels = map[LogComponent]LogLevel{}
}
opts.ComponentLevels[component] = level
return opts
}
// SetMaxDocumentLength sets the maximum length of a document to be logged. Sink is the
// LogSink that will be used to log messages. If this is nil, the driver will use the
// standard logging library.
func (opts *LoggerOptions) SetMaxDocumentLength(maxDocumentLength uint) *LoggerOptions {
opts.MaxDocumentLength = maxDocumentLength
return opts
}
// SetSink sets the LogSink to use for logging. MaxDocumentLength is the maximum length
// of a document to be logged. If the underlying document is larger than this value, it
// will be truncated and appended with an ellipses "...".
func (opts *LoggerOptions) SetSink(sink LogSink) *LoggerOptions {
opts.Sink = sink
return opts
}

View File

@@ -0,0 +1,70 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/bson"
)
var defaultRegistry = bson.NewRegistry()
// Collation allows users to specify language-specific rules for string comparison, such as
// rules for lettercase and accent marks.
type Collation struct {
Locale string `bson:",omitempty"` // The locale
CaseLevel bool `bson:",omitempty"` // The case level
CaseFirst string `bson:",omitempty"` // The case ordering
Strength int `bson:",omitempty"` // The number of comparison levels to use
NumericOrdering bool `bson:",omitempty"` // Whether to order numbers based on numerical order and not collation order
Alternate string `bson:",omitempty"` // Whether spaces and punctuation are considered base characters
MaxVariable string `bson:",omitempty"` // Which characters are affected by alternate: "shifted"
Normalization bool `bson:",omitempty"` // Causes text to be normalized into Unicode NFD
Backwards bool `bson:",omitempty"` // Causes secondary differences to be considered in reverse order, as it is done in the French language
}
// CursorType specifies whether a cursor should close when the last data is retrieved. See
// NonTailable, Tailable, and TailableAwait.
type CursorType int8
const (
// NonTailable specifies that a cursor should close after retrieving the last data.
NonTailable CursorType = iota
// Tailable specifies that a cursor should not close when the last data is retrieved and can be resumed later.
Tailable
// TailableAwait specifies that a cursor should not close when the last data is retrieved and
// that it should block for a certain amount of time for new data before returning no data.
TailableAwait
)
// ReturnDocument specifies whether a findAndUpdate operation should return the document as it was
// before the update or as it is after the update.
type ReturnDocument int8
const (
// Before specifies that findAndUpdate should return the document as it was before the update.
Before ReturnDocument = iota
// After specifies that findAndUpdate should return the document as it is after the update.
After
)
// FullDocument specifies how a change stream should return the modified document.
type FullDocument string
const (
// Default does not include a document copy.
Default FullDocument = "default"
// Off is the same as sending no value for fullDocumentBeforeChange.
Off FullDocument = "off"
// Required is the same as WhenAvailable but raises a server-side error if the post-image is not available.
Required FullDocument = "required"
// UpdateLookup includes a delta describing the changes to the document and a copy of the entire document that
// was changed.
UpdateLookup FullDocument = "updateLookup"
// WhenAvailable includes a post-image of the modified document for replace and update change events
// if the post-image for this event is available.
WhenAvailable FullDocument = "whenAvailable"
)

View File

@@ -0,0 +1,144 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// ReplaceOptions represents arguments that can be used to configure a ReplaceOne
// operation.
//
// See corresponding setter methods for documentation.
type ReplaceOptions struct {
BypassDocumentValidation *bool
Collation *Collation
Comment any
Hint any
Upsert *bool
Let any
Sort any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// ReplaceOptionsBuilder contains options to configure replace operations. Each
// option can be set through setter functions. See documentation for each setter
// function for an explanation of the option.
type ReplaceOptionsBuilder struct {
Opts []func(*ReplaceOptions) error
}
// Replace creates a new ReplaceOptions instance.
func Replace() *ReplaceOptionsBuilder {
return &ReplaceOptionsBuilder{}
}
// List returns a list of CountOptions setter functions.
func (ro *ReplaceOptionsBuilder) List() []func(*ReplaceOptions) error {
return ro.Opts
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true,
// writes executed as part of the operation will opt out of document-level validation on the server.
// The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for
// more information about document validation.
func (ro *ReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *ReplaceOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return ro
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (ro *ReplaceOptionsBuilder) SetCollation(c *Collation) *ReplaceOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error {
opts.Collation = c
return nil
})
return ro
}
// SetComment sets the value for the Comment field. Specifies a string or document that will
// be included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (ro *ReplaceOptionsBuilder) SetComment(comment any) *ReplaceOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error {
opts.Comment = comment
return nil
})
return ro
}
// SetHint sets the value for the Hint field. Specifies the index to use for the
// operation. This should either be the index name as a string or the index
// specification as a document. This option is only valid for MongoDB versions
// >= 4.2. Server versions < 4.2 will return an error if this option is
// specified. The driver will return an error if this option is specified during
// an unacknowledged write operation. The driver will return an error if the
// hint parameter is a multi-key map. The default value is nil, which means that
// no hint will be sent.
func (ro *ReplaceOptionsBuilder) SetHint(h any) *ReplaceOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error {
opts.Hint = h
return nil
})
return ro
}
// SetUpsert sets the value for the Upsert field. If true, a new document will be inserted
// if the filter does not match any documents in the collection. The default value is false.
func (ro *ReplaceOptionsBuilder) SetUpsert(b bool) *ReplaceOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error {
opts.Upsert = &b
return nil
})
return ro
}
// SetLet sets the value for the Let field. Specifies parameters for the aggregate expression.
// This option is only valid for MongoDB versions >= 5.0. Older servers will report an error
// for using this option. This must be a document mapping parameter names to values. Values
// must be constant or closed expressions that do not reference document fields. Parameters
// can then be accessed as variables in an aggregate expression context (e.g. "$$var").
func (ro *ReplaceOptionsBuilder) SetLet(l any) *ReplaceOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error {
opts.Let = l
return nil
})
return ro
}
// SetSort sets the value for the Sort field. Specifies a document specifying which document should
// be replaced if the filter used by the operation matches multiple documents in the collection. If
// set, the first document in the sorted order will be replaced. This option is only valid for MongoDB
// versions >= 8.0. The sort parameter is evaluated sequentially, so the driver will return an error
// if it is a multi-key map (which is unordeded). The default value is nil.
func (ro *ReplaceOptionsBuilder) SetSort(s any) *ReplaceOptionsBuilder {
ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error {
opts.Sort = s
return nil
})
return ro
}

View File

@@ -0,0 +1,57 @@
// Copyright (C) MongoDB, Inc. 2022-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// RewrapManyDataKeyOptions represents all possible options used to decrypt and
// encrypt all matching data keys with a possibly new masterKey.
//
// See corresponding setter methods for documentation.
type RewrapManyDataKeyOptions struct {
Provider *string
MasterKey any
}
// RewrapManyDataKeyOptionsBuilder contains options to configure rewraping a
// data key. Each option can be set through setter functions. See documentation
// for each setter function for an explanation of the option.
type RewrapManyDataKeyOptionsBuilder struct {
Opts []func(*RewrapManyDataKeyOptions) error
}
// RewrapManyDataKey creates a new RewrapManyDataKeyOptions instance.
func RewrapManyDataKey() *RewrapManyDataKeyOptionsBuilder {
return new(RewrapManyDataKeyOptionsBuilder)
}
// List returns a list of CountOptions setter functions.
func (rmdko *RewrapManyDataKeyOptionsBuilder) List() []func(*RewrapManyDataKeyOptions) error {
return rmdko.Opts
}
// SetProvider sets the value for the Provider field. Provider identifies the new KMS provider.
// If omitted, encrypting uses the current KMS provider.
func (rmdko *RewrapManyDataKeyOptionsBuilder) SetProvider(provider string) *RewrapManyDataKeyOptionsBuilder {
rmdko.Opts = append(rmdko.Opts, func(opts *RewrapManyDataKeyOptions) error {
opts.Provider = &provider
return nil
})
return rmdko
}
// SetMasterKey sets the value for the MasterKey field. MasterKey identifies the new masterKey.
// If omitted, rewraps with the current masterKey.
func (rmdko *RewrapManyDataKeyOptionsBuilder) SetMasterKey(masterKey any) *RewrapManyDataKeyOptionsBuilder {
rmdko.Opts = append(rmdko.Opts, func(opts *RewrapManyDataKeyOptions) error {
opts.MasterKey = masterKey
return nil
})
return rmdko
}

View File

@@ -0,0 +1,49 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
)
// RunCmdOptions represents arguments that can be used to configure a RunCommand
// operation.
//
// See corresponding setter methods for documentation.
type RunCmdOptions struct {
ReadPreference *readpref.ReadPref
}
// RunCmdOptionsBuilder contains options to configure runCommand operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type RunCmdOptionsBuilder struct {
Opts []func(*RunCmdOptions) error
}
// RunCmd creates a new RunCmdOptions instance.
func RunCmd() *RunCmdOptionsBuilder {
return &RunCmdOptionsBuilder{}
}
// List returns a list of CountOptions setter functions.
func (rc *RunCmdOptionsBuilder) List() []func(*RunCmdOptions) error {
return rc.Opts
}
// SetReadPreference sets value for the ReadPreference field. Specifies the read preference
// to use for the operation. The default value is nil, which means that the primary read
// preference will be used.
func (rc *RunCmdOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *RunCmdOptionsBuilder {
rc.Opts = append(rc.Opts, func(opts *RunCmdOptions) error {
opts.ReadPreference = rp
return nil
})
return rc
}

View File

@@ -0,0 +1,118 @@
// Copyright (C) MongoDB, Inc. 2023-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// SearchIndexesOptions represents arguments that can be used to configure a
// SearchIndexView.
type SearchIndexesOptions struct {
Name *string
Type *string
}
// SearchIndexesOptionsBuilder contains options to configure search index
// operations. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type SearchIndexesOptionsBuilder struct {
Opts []func(*SearchIndexesOptions) error
}
// SearchIndexes creates a new SearchIndexesOptions instance.
func SearchIndexes() *SearchIndexesOptionsBuilder {
return &SearchIndexesOptionsBuilder{}
}
// List returns a list of CountOptions setter functions.
func (sio *SearchIndexesOptionsBuilder) List() []func(*SearchIndexesOptions) error {
return sio.Opts
}
// SetName sets the value for the Name field.
func (sio *SearchIndexesOptionsBuilder) SetName(name string) *SearchIndexesOptionsBuilder {
sio.Opts = append(sio.Opts, func(opts *SearchIndexesOptions) error {
opts.Name = &name
return nil
})
return sio
}
// SetType sets the value for the Type field.
func (sio *SearchIndexesOptionsBuilder) SetType(typ string) *SearchIndexesOptionsBuilder {
sio.Opts = append(sio.Opts, func(opts *SearchIndexesOptions) error {
opts.Type = &typ
return nil
})
return sio
}
// CreateSearchIndexesOptions represents arguments that can be used to configure
// a SearchIndexView.CreateOne or SearchIndexView.CreateMany operation.
type CreateSearchIndexesOptions struct{}
// CreateSearchIndexesOptionsBuilder contains options to configure creating
// search indexes. Each option can be set through setter functions. See
// documentation for each setter function for an explanation of the option.
type CreateSearchIndexesOptionsBuilder struct {
Opts []func(*CreateSearchIndexesOptions) error
}
// List returns a list of CreateSearchIndexesOptions setter functions.
func (csio *CreateSearchIndexesOptionsBuilder) List() []func(*CreateSearchIndexesOptions) error {
return csio.Opts
}
// ListSearchIndexesOptions represents arguments that can be used to configure a
// SearchIndexView.List operation.
type ListSearchIndexesOptions struct {
AggregateOptions *AggregateOptions
}
// ListSearchIndexesOptionsBuilder contains options that can be used to
// configure a SearchIndexView.List operation.
type ListSearchIndexesOptionsBuilder struct {
Opts []func(*ListSearchIndexesOptions) error
}
// List returns a list of ListSearchIndexesOptions setter functions.
func (lsi *ListSearchIndexesOptionsBuilder) List() []func(*ListSearchIndexesOptions) error {
return lsi.Opts
}
// DropSearchIndexOptions represents arguments that can be used to configure a
// SearchIndexView.DropOne operation.
type DropSearchIndexOptions struct{}
// DropSearchIndexOptionsBuilder contains options to configure dropping search
// indexes. Each option can be set through setter functions. See documentation
// for each setter function for an explanation of the option.
type DropSearchIndexOptionsBuilder struct {
Opts []func(*DropSearchIndexOptions) error
}
// List returns a list of DropSearchIndexOptions setter functions.
func (dsio *DropSearchIndexOptionsBuilder) List() []func(*DropSearchIndexOptions) error {
return dsio.Opts
}
// UpdateSearchIndexOptions represents arguments that can be used to configure a
// SearchIndexView.UpdateOne operation.
type UpdateSearchIndexOptions struct{}
// UpdateSearchIndexOptionsBuilder contains options to configure updating search
// indexes. Each option can be set through setter functions. See documentation
// for each setter function for an explanation of the option.
type UpdateSearchIndexOptionsBuilder struct {
Opts []func(*UpdateSearchIndexOptions) error
}
// List returns a list of UpdateSearchIndexOptions setter functions.
func (usio *UpdateSearchIndexOptionsBuilder) List() []func(*UpdateSearchIndexOptions) error {
return usio.Opts
}

View File

@@ -0,0 +1,66 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"fmt"
)
// ServerAPIOptions represents arguments used to configure the API version sent to
// the server when running commands.
//
// Sending a specified server API version causes the server to behave in a
// manner compatible with that API version. It also causes the driver to behave
// in a manner compatible with the drivers behavior as of the release when the
// driver first started to support the specified server API version.
//
// The user must specify a ServerAPIVersion if including ServerAPIOptions in
// their client. That version must also be currently supported by the driver.
// This version of the driver supports API version "1".
//
// See corresponding setter methods for documentation.
type ServerAPIOptions struct {
ServerAPIVersion ServerAPIVersion
Strict *bool
DeprecationErrors *bool
}
// ServerAPI creates a new ServerAPIOptions configured with the provided
// serverAPIversion.
func ServerAPI(serverAPIVersion ServerAPIVersion) *ServerAPIOptions {
return &ServerAPIOptions{ServerAPIVersion: serverAPIVersion}
}
// SetStrict specifies whether the server should return errors for features that are not part of the API version.
func (s *ServerAPIOptions) SetStrict(strict bool) *ServerAPIOptions {
s.Strict = &strict
return s
}
// SetDeprecationErrors specifies whether the server should return errors for deprecated features.
func (s *ServerAPIOptions) SetDeprecationErrors(deprecationErrors bool) *ServerAPIOptions {
s.DeprecationErrors = &deprecationErrors
return s
}
// ServerAPIVersion represents an API version that can be used in ServerAPIOptions.
type ServerAPIVersion string
const (
// ServerAPIVersion1 is the first API version.
ServerAPIVersion1 ServerAPIVersion = "1"
)
// Validate determines if the provided ServerAPIVersion is currently supported by the driver.
func (sav ServerAPIVersion) Validate() error {
if sav == ServerAPIVersion1 {
return nil
}
return fmt.Errorf("api version %q not supported; this driver version only supports API version \"1\"", sav)
}

View File

@@ -0,0 +1,87 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/bson"
// DefaultCausalConsistency is the default value for the CausalConsistency option.
var DefaultCausalConsistency = true
// SessionOptions represents arguments that can be used to configure a Session.
//
// See corresponding setter methods for documentation.
type SessionOptions struct {
CausalConsistency *bool
DefaultTransactionOptions *TransactionOptionsBuilder
Snapshot *bool
SnapshotTime *bson.Timestamp
}
// SessionOptionsBuilder represents functional options that configure a Sessionopts.
type SessionOptionsBuilder struct {
Opts []func(*SessionOptions) error
}
// Session creates a new SessionOptions instance.
func Session() *SessionOptionsBuilder {
return &SessionOptionsBuilder{}
}
// List returns a list of SessionOptions setter functions.
func (s *SessionOptionsBuilder) List() []func(*SessionOptions) error {
return s.Opts
}
// SetCausalConsistency sets the value for the CausalConsistency field. If true, causal
// consistency will be enabled for the session. This option cannot be set to true if Snapshot
// is set to true. The default value is true unless Snapshot is set to true. See
// https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency/#sessions
// for more information.
func (s *SessionOptionsBuilder) SetCausalConsistency(b bool) *SessionOptionsBuilder {
s.Opts = append(s.Opts, func(opts *SessionOptions) error {
opts.CausalConsistency = &b
return nil
})
return s
}
// SetDefaultTransactionOptions sets the value for the DefaultTransactionOptions field.
// Specifies the default options for transactions started in the session. If this object
// or any value on the object is nil, the client-level read concern, write concern,
// and/or read preference will be used to start the session.
func (s *SessionOptionsBuilder) SetDefaultTransactionOptions(dt *TransactionOptionsBuilder) *SessionOptionsBuilder {
s.Opts = append(s.Opts, func(opts *SessionOptions) error {
opts.DefaultTransactionOptions = dt
return nil
})
return s
}
// SetSnapshot sets the value for the Snapshot field. If true, all read operations performed
// with this session will be read from the same snapshot. This option cannot be set to true
// if CausalConsistency is set to true. Transactions and write operations are not allowed on
// snapshot sessions and will error. The default value is false.
func (s *SessionOptionsBuilder) SetSnapshot(b bool) *SessionOptionsBuilder {
s.Opts = append(s.Opts, func(opts *SessionOptions) error {
opts.Snapshot = &b
return nil
})
return s
}
// SetSnapshotTime sets the value for the SnapshotTime field. Specifies the
// timestamp to use for snapshot reads within the session. This option can only
// be set if Snapshot is set to true. If not provided, the snapshot time will be
// determined automatically from the atClusterTime of the first read operation
// performed in the session. The default value is nil.
func (s *SessionOptionsBuilder) SetSnapshotTime(t bson.Timestamp) *SessionOptionsBuilder {
s.Opts = append(s.Opts, func(opts *SessionOptions) error {
opts.SnapshotTime = &t
return nil
})
return s
}

View File

@@ -0,0 +1,79 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)
// TransactionOptions represents arguments that can be used to configure a
// transaction.
//
// See corresponding setter methods for documentation.
type TransactionOptions struct {
ReadConcern *readconcern.ReadConcern
ReadPreference *readpref.ReadPref
WriteConcern *writeconcern.WriteConcern
}
// TransactionOptionsBuilder contains arguments to configure count operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type TransactionOptionsBuilder struct {
Opts []func(*TransactionOptions) error
}
// Transaction creates a new TransactionOptions instance.
func Transaction() *TransactionOptionsBuilder {
return &TransactionOptionsBuilder{}
}
// List returns a list of TransactionOptions setter functions.
func (t *TransactionOptionsBuilder) List() []func(*TransactionOptions) error {
return t.Opts
}
// SetReadConcern sets the value for the ReadConcern field. Specifies the read concern for operations
// in the transaction. The default value is nil, which means that the default read concern of the
// session used to start the transaction will be used.
func (t *TransactionOptionsBuilder) SetReadConcern(rc *readconcern.ReadConcern) *TransactionOptionsBuilder {
t.Opts = append(t.Opts, func(opts *TransactionOptions) error {
opts.ReadConcern = rc
return nil
})
return t
}
// SetReadPreference sets the value for the ReadPreference field. Specifies the read preference for
// operations in the transaction. The default value is nil, which means that the default read
// preference of the session used to start the transaction will be used.
func (t *TransactionOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *TransactionOptionsBuilder {
t.Opts = append(t.Opts, func(opts *TransactionOptions) error {
opts.ReadPreference = rp
return nil
})
return t
}
// SetWriteConcern sets the value for the WriteConcern field. Specifies the write concern for
// operations in the transaction. The default value is nil, which means that the default
// write concern of the session used to start the transaction will be used.
func (t *TransactionOptionsBuilder) SetWriteConcern(wc *writeconcern.WriteConcern) *TransactionOptionsBuilder {
t.Opts = append(t.Opts, func(opts *TransactionOptions) error {
opts.WriteConcern = wc
return nil
})
return t
}

View File

@@ -0,0 +1,293 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/v2/internal/optionsutil"
// UpdateOneOptions represents arguments that can be used to configure UpdateOne
// operations.
//
// See corresponding setter methods for documentation.
type UpdateOneOptions struct {
ArrayFilters []any
BypassDocumentValidation *bool
Collation *Collation
Comment any
Hint any
Upsert *bool
Let any
Sort any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// UpdateOneOptionsBuilder contains options to configure UpdateOne operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type UpdateOneOptionsBuilder struct {
Opts []func(*UpdateOneOptions) error
}
// UpdateOne creates a new UpdateOneOptions instance.
func UpdateOne() *UpdateOneOptionsBuilder {
return &UpdateOneOptionsBuilder{}
}
// List returns a list of UpdateOneOptions setter functions.
func (uo *UpdateOneOptionsBuilder) List() []func(*UpdateOneOptions) error {
return uo.Opts
}
// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a
// set of filters specifying to which array elements an update should apply. The
// default value is nil, which means the update will apply to all array
// elements.
func (uo *UpdateOneOptionsBuilder) SetArrayFilters(af []any) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.ArrayFilters = af
return nil
})
return uo
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true,
// writes executed as part of the operation will opt out of document-level validation on the server.
// The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for
// more information about document validation.
func (uo *UpdateOneOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return uo
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (uo *UpdateOneOptionsBuilder) SetCollation(c *Collation) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.Collation = c
return nil
})
return uo
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (uo *UpdateOneOptionsBuilder) SetComment(comment any) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.Comment = comment
return nil
})
return uo
}
// SetHint sets the value for the Hint field. Specifies the index to use for the
// operation. This should either be the index name as a string or the index
// specification as a document. This option is only valid for MongoDB versions
// >= 4.2. Server versions < 4.2 will return an error if this option is
// specified. The driver will return an error if this option is specified during
// an unacknowledged write operation. The driver will return an error if the
// hint parameter is a multi-key map. The default value is nil, which means that
// no hint will be sent.
func (uo *UpdateOneOptionsBuilder) SetHint(h any) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.Hint = h
return nil
})
return uo
}
// SetUpsert sets the value for the Upsert field. If true, a new document will be inserted if the
// filter does not match any documents in the collection. The default value is false.
func (uo *UpdateOneOptionsBuilder) SetUpsert(b bool) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.Upsert = &b
return nil
})
return uo
}
// SetLet sets the value for the Let field. Specifies parameters for the update expression. This
// option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using
// this option. This must be a document mapping parameter names to values. Values must be constant
// or closed expressions that do not reference document fields. Parameters can then be accessed
// as variables in an aggregate expression context (e.g. "$$var").
func (uo *UpdateOneOptionsBuilder) SetLet(l any) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.Let = l
return nil
})
return uo
}
// SetSort sets the value for the Sort field. Specifies a document specifying which document should
// be updated if the filter used by the operation matches multiple documents in the collection. If
// set, the first document in the sorted order will be updated. This option is only valid for MongoDB
// versions >= 8.0. The sort parameter is evaluated sequentially, so the driver will return an error
// if it is a multi-key map (which is unordeded). The default value is nil.
func (uo *UpdateOneOptionsBuilder) SetSort(s any) *UpdateOneOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error {
opts.Sort = s
return nil
})
return uo
}
// UpdateManyOptions represents arguments that can be used to configure UpdateMany
// operations.
//
// See corresponding setter methods for documentation.
type UpdateManyOptions struct {
ArrayFilters []any
BypassDocumentValidation *bool
Collation *Collation
Comment any
Hint any
Upsert *bool
Let any
// Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any
// release.
Internal optionsutil.Options
}
// UpdateManyOptionsBuilder contains options to configure UpdateMany operations.
// Each option can be set through setter functions. See documentation for each
// setter function for an explanation of the option.
type UpdateManyOptionsBuilder struct {
Opts []func(*UpdateManyOptions) error
}
// UpdateMany creates a new UpdateManyOptions instance.
func UpdateMany() *UpdateManyOptionsBuilder {
return &UpdateManyOptionsBuilder{}
}
// List returns a list of UpdateManyOptions setter functions.
func (uo *UpdateManyOptionsBuilder) List() []func(*UpdateManyOptions) error {
return uo.Opts
}
// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a
// set of filters specifying to which array elements an update should apply. The
// default value is nil, which means the update will apply to all array
// elements.
func (uo *UpdateManyOptionsBuilder) SetArrayFilters(af []any) *UpdateManyOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error {
opts.ArrayFilters = af
return nil
})
return uo
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true,
// writes executed as part of the operation will opt out of document-level validation on the server.
// The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for
// more information about document validation.
func (uo *UpdateManyOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateManyOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error {
opts.BypassDocumentValidation = &b
return nil
})
return uo
}
// SetCollation sets the value for the Collation field. Specifies a collation to
// use for string comparisons during the operation. The default value is nil,
// which means the default collation of the collection will be used.
func (uo *UpdateManyOptionsBuilder) SetCollation(c *Collation) *UpdateManyOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error {
opts.Collation = c
return nil
})
return uo
}
// SetComment sets the value for the Comment field. Specifies a string or document that will be
// included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default value is nil, which means that no comment will be included in the logs.
func (uo *UpdateManyOptionsBuilder) SetComment(comment any) *UpdateManyOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error {
opts.Comment = comment
return nil
})
return uo
}
// SetHint sets the value for the Hint field. Specifies the index to use for the
// operation. This should either be the index name as a string or the index
// specification as a document. This option is only valid for MongoDB versions
// >= 4.2. Server versions < 4.2 will return an error if this option is
// specified. The driver will return an error if this option is specified during
// an unacknowledged write operation. The driver will return an error if the
// hint parameter is a multi-key map. The default value is nil, which means that
// no hint will be sent.
func (uo *UpdateManyOptionsBuilder) SetHint(h any) *UpdateManyOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error {
opts.Hint = h
return nil
})
return uo
}
// SetUpsert sets the value for the Upsert field. If true, a new document will be inserted if the
// filter does not match any documents in the collection. The default value is false.
func (uo *UpdateManyOptionsBuilder) SetUpsert(b bool) *UpdateManyOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error {
opts.Upsert = &b
return nil
})
return uo
}
// SetLet sets the value for the Let field. Specifies parameters for the update expression. This
// option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using
// this option. This must be a document mapping parameter names to values. Values must be constant
// or closed expressions that do not reference document fields. Parameters can then be accessed
// as variables in an aggregate expression context (e.g. "$$var").
func (uo *UpdateManyOptionsBuilder) SetLet(l any) *UpdateManyOptionsBuilder {
uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error {
opts.Let = l
return nil
})
return uo
}