Documentation
¶
Overview ¶
Package mongo provides a MongoDB client wrapper with convenient methods for connection management and database operations.
Key features:
- Functional options pattern for configuration
- Thread-safe operations with connection pooling
- Context support for all operations
- Generic CRUD operations with dynamic queries
- Graceful shutdown with proper cleanup
Basic usage:
client, err := mongo.New(
mongo.DefaultConfig(),
mongo.WithURI("mongodb://localhost:27017"),
mongo.WithDatabase("myapp"),
)
if err != nil {
panic(err)
}
defer client.Close(context.Background())
Index ¶
- Variables
- type A
- type AggregateOptions
- type AggregationBuilder
- func (ab *AggregationBuilder) AddStage(stage bson.D) *AggregationBuilder
- func (ab *AggregationBuilder) Build() []bson.D
- func (ab *AggregationBuilder) Group(id interface{}, fields bson.M) *AggregationBuilder
- func (ab *AggregationBuilder) Limit(limit int64) *AggregationBuilder
- func (ab *AggregationBuilder) Lookup(from, localField, foreignField, as string) *AggregationBuilder
- func (ab *AggregationBuilder) Match(filter interface{}) *AggregationBuilder
- func (ab *AggregationBuilder) Project(projection interface{}) *AggregationBuilder
- func (ab *AggregationBuilder) Skip(skip int64) *AggregationBuilder
- func (ab *AggregationBuilder) Sort(sort interface{}) *AggregationBuilder
- func (ab *AggregationBuilder) Unwind(path string) *AggregationBuilder
- type BulkWriteOptions
- type Client
- func (c *Client) Aggregate(ctx context.Context, collection string, pipeline any, results any, ...) error
- func (c *Client) BulkWrite(ctx context.Context, collection string, models []mongo.WriteModel, ...) (*mongo.BulkWriteResult, error)
- func (c *Client) Close(ctx context.Context) error
- func (c *Client) CountDocuments(ctx context.Context, collection string, filter any, ...) (int64, error)
- func (c *Client) CreateCollection(ctx context.Context, collection string, ...) error
- func (c *Client) CreateCollections(ctx context.Context, collections map[string]*options.CreateCollectionOptions) error
- func (c *Client) CreateIndex(ctx context.Context, collection string, keys any, ...) (string, error)
- func (c *Client) CreateIndexes(ctx context.Context, indexes map[string][]mongo.IndexModel) (map[string][]string, error)
- func (c *Client) DeleteMany(ctx context.Context, collection string, filter any, ...) (*mongo.DeleteResult, error)
- func (c *Client) DeleteOne(ctx context.Context, collection string, filter any, ...) (*mongo.DeleteResult, error)
- func (c *Client) Distinct(ctx context.Context, collection string, fieldName string, filter any, ...) ([]any, error)
- func (c *Client) DropIndex(ctx context.Context, collection string, indexName string) error
- func (c *Client) Find(ctx context.Context, collection string, filter any, results any, ...) error
- func (c *Client) FindOne(ctx context.Context, collection string, filter any, result any, ...) error
- func (c *Client) FindOneAndDelete(ctx context.Context, collection string, filter any, result any, ...) error
- func (c *Client) FindOneAndReplace(ctx context.Context, collection string, filter any, replacement any, ...) error
- func (c *Client) FindOneAndUpdate(ctx context.Context, collection string, filter any, update any, result any, ...) error
- func (c *Client) GetCollection(collectionName string) *mongo.Collection
- func (c *Client) GetCollectionFrom(databaseName, collectionName string) *mongo.Collection
- func (c *Client) GetConfig() models.Config
- func (c *Client) GetDatabase(name string) *mongo.Database
- func (c *Client) InsertMany(ctx context.Context, collection string, documents []any) (*mongo.InsertManyResult, error)
- func (c *Client) InsertOne(ctx context.Context, collection string, document any) (*mongo.InsertOneResult, error)
- func (c *Client) IsClosed() bool
- func (c *Client) IsConnected(ctx context.Context) bool
- func (c *Client) ListCollections(ctx context.Context) ([]string, error)
- func (c *Client) ListDatabases(ctx context.Context, filter interface{}) ([]string, error)
- func (c *Client) ListIndexes(ctx context.Context, collection string) ([]bson.M, error)
- func (c *Client) Ping(ctx context.Context) error
- func (c *Client) ReplaceOne(ctx context.Context, collection string, filter any, replacement any, ...) (*mongo.UpdateResult, error)
- func (c *Client) StartSession(opts ...*options.SessionOptions) (mongo.Session, error)
- func (c *Client) UpdateMany(ctx context.Context, collection string, filter any, update any, ...) (*mongo.UpdateResult, error)
- func (c *Client) UpdateOne(ctx context.Context, collection string, filter any, update any, ...) (*mongo.UpdateResult, error)
- func (c *Client) UseSession(ctx context.Context, fn func(mongo.SessionContext) error) error
- type Config
- type CountOptions
- type CreateCollectionOptions
- type D
- type DeleteOptions
- type DistinctOptions
- type E
- type FindOneAndDeleteOptions
- type FindOneAndReplaceOptions
- type FindOneAndUpdateOptions
- type FindOneOptions
- type FindOptions
- type IndexModel
- type IndexOptions
- type InsertManyOptions
- type InsertOneOptions
- type M
- type ObjectID
- type Option
- type QueryBuilder
- func (qb *QueryBuilder) And(conditions ...bson.D) *QueryBuilder
- func (qb *QueryBuilder) Build() (bson.D, *options.FindOptions)
- func (qb *QueryBuilder) BuildFilter() bson.D
- func (qb *QueryBuilder) BuildOptions() *options.FindOptions
- func (qb *QueryBuilder) Equals(key string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Exists(key string, exists bool) *QueryBuilder
- func (qb *QueryBuilder) Filter(key string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) GreaterThan(key string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) GreaterThanOrEqual(key string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) In(key string, values ...interface{}) *QueryBuilder
- func (qb *QueryBuilder) LessThan(key string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) LessThanOrEqual(key string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Limit(limit int64) *QueryBuilder
- func (qb *QueryBuilder) Nor(conditions ...bson.D) *QueryBuilder
- func (qb *QueryBuilder) NotEquals(key string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) NotIn(key string, values ...interface{}) *QueryBuilder
- func (qb *QueryBuilder) Or(conditions ...bson.D) *QueryBuilder
- func (qb *QueryBuilder) Project(projection interface{}) *QueryBuilder
- func (qb *QueryBuilder) Regex(key string, pattern string, options string) *QueryBuilder
- func (qb *QueryBuilder) Skip(skip int64) *QueryBuilder
- func (qb *QueryBuilder) Sort(field string, ascending bool) *QueryBuilder
- func (qb *QueryBuilder) SortBy(sort interface{}) *QueryBuilder
- type ReplaceOptions
- type UpdateBuilder
- func (ub *UpdateBuilder) AddToSet(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Build() bson.D
- func (ub *UpdateBuilder) CurrentDate(key string) *UpdateBuilder
- func (ub *UpdateBuilder) Inc(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Max(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Min(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Mul(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Pop(key string, first bool) *UpdateBuilder
- func (ub *UpdateBuilder) Pull(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Push(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Rename(oldName string, newName string) *UpdateBuilder
- func (ub *UpdateBuilder) Set(key string, value interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) SetMultiple(fields map[string]interface{}) *UpdateBuilder
- func (ub *UpdateBuilder) Unset(keys ...string) *UpdateBuilder
- type UpdateOptions
- type WriteModel
Constants ¶
This section is empty.
Variables ¶
var ( // WithURI sets the MongoDB connection URI WithURI = models.WithURI // WithDatabase sets the default database name WithDatabase = models.WithDatabase // WithMaxPoolSize sets the maximum connection pool size WithMaxPoolSize = models.WithMaxPoolSize // WithMinPoolSize sets the minimum connection pool size WithMinPoolSize = models.WithMinPoolSize // WithConnectTimeout sets the connection timeout WithConnectTimeout = models.WithConnectTimeout // WithServerSelectionTimeout sets the server selection timeout WithServerSelectionTimeout = models.WithServerSelectionTimeout // WithSocketTimeout sets the socket operation timeout WithSocketTimeout = models.WithSocketTimeout // WithTimeout sets the default operation timeout WithTimeout = models.WithTimeout // WithDebug enables or disables debug logging WithDebug = models.WithDebug // WithRetryWrites enables or disables automatic retry of write operations WithRetryWrites = models.WithRetryWrites // WithRetryReads enables or disables automatic retry of read operations WithRetryReads = models.WithRetryReads // WithAppName sets the application name for MongoDB logs WithAppName = models.WithAppName // WithDirectConnection sets whether to connect directly to a single host WithDirectConnection = models.WithDirectConnection // WithReplicaSet sets the replica set name WithReplicaSet = models.WithReplicaSet // WithReadPreference sets the read preference mode WithReadPreference = models.WithReadPreference // WithMaxConnIdleTime sets the maximum idle time for connections WithMaxConnIdleTime = models.WithMaxConnIdleTime // WithHeartbeatInterval sets the interval between server heartbeats WithHeartbeatInterval = models.WithHeartbeatInterval )
var ( // ErrInvalidConfig returns a configuration error with the given message ErrInvalidConfig = errors.ErrInvalidConfig // ErrConnectionFailed returns an error indicating connection failure ErrConnectionFailed = errors.ErrConnectionFailed // ErrClientClosed returns an error indicating the client is closed ErrClientClosed = errors.ErrClientClosed // ErrInvalidOperation returns an error indicating an invalid operation ErrInvalidOperation = errors.ErrInvalidOperation // ErrDatabaseNotFound returns an error indicating database was not found ErrDatabaseNotFound = errors.ErrDatabaseNotFound // ErrCollectionNotFound returns an error indicating collection was not found ErrCollectionNotFound = errors.ErrCollectionNotFound // NewOperationError creates a new operation error NewOperationError = errors.NewOperationError )
Re-export custom error functions
var ( // ToObjectID converts a string to MongoDB ObjectID ToObjectID = helpers.ToObjectID // ToObjectIDs converts multiple strings to MongoDB ObjectIDs ToObjectIDs = helpers.ToObjectIDs // IsValidObjectID checks if a string is a valid MongoDB ObjectID IsValidObjectID = helpers.IsValidObjectID // NewObjectID generates a new MongoDB ObjectID NewObjectID = helpers.NewObjectID // ToBSON converts a map to BSON document ToBSON = helpers.ToBSON // ToBSONArray converts a slice of maps to BSON array ToBSONArray = helpers.ToBSONArray // MergeBSON merges multiple BSON documents MergeBSON = helpers.MergeBSON // BSONToMap converts a BSON document to a map BSONToMap = helpers.BSONToMap )
Re-export helper functions
var ( // ErrNoDocuments is returned when a query that expects a document doesn't find one ErrNoDocuments = mongo.ErrNoDocuments // ErrNilDocument is returned when a nil document is passed to an insert operation ErrNilDocument = mongo.ErrNilDocument // ErrNilValue is returned when a nil value is passed where it's not allowed ErrNilValue = mongo.ErrNilValue // ErrEmptySlice is returned when an empty slice is passed where it's not allowed ErrEmptySlice = mongo.ErrEmptySlice // ErrUnacknowledgedWrite is returned when attempting to get results from an unacknowledged write ErrUnacknowledgedWrite = mongo.ErrUnacknowledgedWrite // ErrClientDisconnected is returned when an operation is attempted on a disconnected client ErrClientDisconnected = mongo.ErrClientDisconnected // ErrInvalidIndexValue is returned when an invalid index value is encountered ErrInvalidIndexValue = mongo.ErrInvalidIndexValue // ErrInvalidObjectID is returned when an invalid ObjectID hex string is provided ErrInvalidObjectID = primitive.ErrInvalidHex )
Re-export MongoDB driver sentinel errors for use with errors.Is()
var ( // IsDuplicateKeyError checks if an error is a duplicate key error (E11000) IsDuplicateKeyError = mongo.IsDuplicateKeyError // IsTimeout checks if an error is a timeout error IsTimeout = mongo.IsTimeout // IsNetworkError checks if an error is a network error IsNetworkError = mongo.IsNetworkError )
Re-export MongoDB driver error helper functions
var ( // Index creates a new IndexOptions instance for configuring index creation Index = options.Index // Find creates a new FindOptions instance for configuring find operations Find = options.Find // FindOne creates a new FindOneOptions instance for configuring findOne operations FindOne = options.FindOne // Update creates a new UpdateOptions instance for configuring update operations Update = options.Update // Replace creates a new ReplaceOptions instance for configuring replace operations Replace = options.Replace // Delete creates a new DeleteOptions instance for configuring delete operations Delete = options.Delete // InsertOne creates a new InsertOneOptions instance for configuring insertOne operations InsertOne = options.InsertOne // InsertMany creates a new InsertManyOptions instance for configuring insertMany operations InsertMany = options.InsertMany // CreateCollection creates a new CreateCollectionOptions instance for configuring collection creation CreateCollection = options.CreateCollection // Aggregate creates a new AggregateOptions instance for configuring aggregate operations Aggregate = options.Aggregate // Count creates a new CountOptions instance for configuring count operations Count = options.Count // Distinct creates a new DistinctOptions instance for configuring distinct operations Distinct = options.Distinct // FindOneAndUpdate creates a new FindOneAndUpdateOptions instance FindOneAndUpdate = options.FindOneAndUpdate // FindOneAndReplace creates a new FindOneAndReplaceOptions instance FindOneAndReplace = options.FindOneAndReplace // FindOneAndDelete creates a new FindOneAndDeleteOptions instance FindOneAndDelete = options.FindOneAndDelete // BulkWrite creates a new BulkWriteOptions instance for configuring bulk write operations BulkWrite = options.BulkWrite )
Options constructors for convenience
var ( // DefaultConfig returns a Config with sensible default values DefaultConfig = models.DefaultConfig )
Functions ¶
This section is empty.
Types ¶
type AggregateOptions ¶
type AggregateOptions = options.AggregateOptions
AggregateOptions is a convenient alias for options.AggregateOptions
type AggregationBuilder ¶
type AggregationBuilder struct {
// contains filtered or unexported fields
}
AggregationBuilder provides a fluent interface for building aggregation pipelines
func NewAggregationBuilder ¶
func NewAggregationBuilder() *AggregationBuilder
NewAggregationBuilder creates a new AggregationBuilder instance
func (*AggregationBuilder) AddStage ¶
func (ab *AggregationBuilder) AddStage(stage bson.D) *AggregationBuilder
AddStage adds a custom pipeline stage
func (*AggregationBuilder) Build ¶
func (ab *AggregationBuilder) Build() []bson.D
Build returns the aggregation pipeline
func (*AggregationBuilder) Group ¶
func (ab *AggregationBuilder) Group(id interface{}, fields bson.M) *AggregationBuilder
Group adds a $group stage
func (*AggregationBuilder) Limit ¶
func (ab *AggregationBuilder) Limit(limit int64) *AggregationBuilder
Limit adds a $limit stage
func (*AggregationBuilder) Lookup ¶
func (ab *AggregationBuilder) Lookup(from, localField, foreignField, as string) *AggregationBuilder
Lookup adds a $lookup stage for joins
func (*AggregationBuilder) Match ¶
func (ab *AggregationBuilder) Match(filter interface{}) *AggregationBuilder
Match adds a $match stage
func (*AggregationBuilder) Project ¶
func (ab *AggregationBuilder) Project(projection interface{}) *AggregationBuilder
Project adds a $project stage
func (*AggregationBuilder) Skip ¶
func (ab *AggregationBuilder) Skip(skip int64) *AggregationBuilder
Skip adds a $skip stage
func (*AggregationBuilder) Sort ¶
func (ab *AggregationBuilder) Sort(sort interface{}) *AggregationBuilder
Sort adds a $sort stage
func (*AggregationBuilder) Unwind ¶
func (ab *AggregationBuilder) Unwind(path string) *AggregationBuilder
Unwind adds an $unwind stage
type BulkWriteOptions ¶
type BulkWriteOptions = options.BulkWriteOptions
BulkWriteOptions is a convenient alias for options.BulkWriteOptions
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps MongoDB client with convenience methods It is safe for concurrent use across goroutines
func New ¶
New creates a new MongoDB client with the given configuration Configuration uses the functional options pattern for flexibility
func (*Client) Aggregate ¶
func (c *Client) Aggregate(ctx context.Context, collection string, pipeline any, results any, opts ...*options.AggregateOptions) error
Aggregate executes an aggregation pipeline and decodes the results.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to aggregate on
- pipeline: Aggregation pipeline stages as a slice (e.g., []bson.M, mongo.Pipeline)
- results: Pointer to a slice where aggregation results will be decoded (e.g., *[]bson.M, *[]User)
- opts: Optional AggregateOptions for batch size, collation, etc.
Returns:
- error: Returns error if operation fails or client is closed
Example:
pipeline := []bson.M{
{"$match": bson.M{"status": "active"}},
{"$group": bson.M{"_id": "$country", "count": bson.M{"$sum": 1}}},
{"$sort": bson.M{"count": -1}},
}
var results []bson.M
err := client.Aggregate(ctx, "users", pipeline, &results)
if err != nil {
log.Fatal(err)
}
for _, result := range results {
fmt.Printf("Country: %s, Count: %d\n", result["_id"], result["count"])
}
func (*Client) BulkWrite ¶
func (c *Client) BulkWrite(ctx context.Context, collection string, models []mongo.WriteModel, opts ...*options.BulkWriteOptions) (*mongo.BulkWriteResult, error)
BulkWrite executes multiple write operations (insert, update, delete) in a single batch. This is more efficient than executing operations individually when performing multiple writes.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to write to
- models: Slice of write models (mongo.InsertOneModel, mongo.UpdateOneModel, mongo.DeleteOneModel, etc.)
- opts: Optional BulkWriteOptions for ordered execution, bypass validation, etc.
Returns:
- *mongo.BulkWriteResult: Contains InsertedCount, MatchedCount, ModifiedCount, DeletedCount, UpsertedCount, and UpsertedIDs
- error: Returns error if operation fails or client is closed
Example:
models := []mongo.WriteModel{
mongo.NewInsertOneModel().SetDocument(User{Name: "Alice", Email: "alice@example.com"}),
mongo.NewUpdateOneModel().SetFilter(bson.M{"name": "Bob"}).SetUpdate(bson.M{"$set": bson.M{"status": "active"}}),
mongo.NewDeleteOneModel().SetFilter(bson.M{"name": "Charlie"}),
}
result, err := client.BulkWrite(ctx, "users", models)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Inserted: %d, Modified: %d, Deleted: %d\n", result.InsertedCount, result.ModifiedCount, result.DeletedCount)
func (*Client) Close ¶
Close closes the MongoDB client connection gracefully After calling Close, the client should not be used
func (*Client) CountDocuments ¶
func (c *Client) CountDocuments(ctx context.Context, collection string, filter any, opts ...*options.CountOptions) (int64, error)
CountDocuments counts the number of documents matching the filter.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to count in
- filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} to count all documents
- opts: Optional CountOptions for limit, skip, collation, etc.
Returns:
- int64: The number of documents matching the filter
- error: Returns error if operation fails or client is closed
Example:
filter := bson.M{"status": "active"}
count, err := client.CountDocuments(ctx, "users", filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d active users\n", count)
func (*Client) CreateCollection ¶
func (c *Client) CreateCollection(ctx context.Context, collection string, opts ...*options.CreateCollectionOptions) error
CreateCollection explicitly creates a new collection in the default database. Note: MongoDB creates collections automatically on first insert, but this method is useful for creating collections with specific options like validation, capped collections, or time series.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to create
- opts: Optional CreateCollectionOptions for validation, capped collections, time series, collation, etc.
Returns:
- error: Returns error if collection already exists, operation fails, or client is closed
Example:
// Create a simple collection
err := client.CreateCollection(ctx, "users")
// Create a capped collection (fixed size, FIFO)
cappedOpts := options.CreateCollection().
SetCapped(true).
SetSizeInBytes(1048576). // 1MB
SetMaxDocuments(1000)
err := client.CreateCollection(ctx, "logs", cappedOpts)
// Create collection with schema validation
validator := bson.M{
"$jsonSchema": bson.M{
"bsonType": "object",
"required": []string{"name", "email"},
"properties": bson.M{
"name": bson.M{"bsonType": "string"},
"email": bson.M{"bsonType": "string"},
"age": bson.M{"bsonType": "int", "minimum": 0},
},
},
}
validatorOpts := options.CreateCollection().SetValidator(validator)
err := client.CreateCollection(ctx, "validated_users", validatorOpts)
func (*Client) CreateCollections ¶
func (c *Client) CreateCollections(ctx context.Context, collections map[string]*options.CreateCollectionOptions) error
CreateCollections creates multiple collections in the default database in a single operation. This is useful for initializing a database schema with multiple collections at once.
Parameters:
- ctx: Context for cancellation and timeout control
- collections: Map where keys are collection names and values are optional CreateCollectionOptions (can be nil)
Returns:
- error: Returns error if any collection creation fails or client is closed
Note: If one collection fails to create, subsequent collections will not be attempted. Consider using error handling to manage partial failures if needed.
Example:
// Create multiple collections with different options
collections := map[string]*options.CreateCollectionOptions{
"users": nil, // Simple collection, no special options
"products": nil,
"logs": options.CreateCollection(). // Capped collection for logs
SetCapped(true).
SetSizeInBytes(5242880). // 5MB
SetMaxDocuments(10000),
"orders": options.CreateCollection(). // Collection with validation
SetValidator(bson.M{
"$jsonSchema": bson.M{
"bsonType": "object",
"required": []string{"user_id", "total"},
},
}),
}
err := client.CreateCollections(ctx, collections)
if err != nil {
log.Fatal(err)
}
fmt.Println("All collections created successfully")
func (*Client) CreateIndex ¶
func (c *Client) CreateIndex(ctx context.Context, collection string, keys any, opts ...*options.IndexOptions) (string, error)
CreateIndex creates a new index on the specified collection to improve query performance.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to create the index on
- keys: Index keys specification (e.g., bson.M{"email": 1} for ascending, bson.M{"age": -1} for descending)
- opts: Optional IndexOptions for unique, sparse, partial filters, TTL, etc.
Returns:
- string: The name of the created index
- error: Returns error if operation fails or client is closed
Example:
// Create unique index on email field
keys := bson.M{"email": 1}
opts := options.Index().SetUnique(true)
indexName, err := client.CreateIndex(ctx, "users", keys, opts)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created index: %s\n", indexName)
// Create compound index on multiple fields
compoundKeys := bson.D{{"country", 1}, {"city", 1}, {"created_at", -1}}
indexName, err := client.CreateIndex(ctx, "users", compoundKeys)
func (*Client) CreateIndexes ¶
func (c *Client) CreateIndexes(ctx context.Context, indexes map[string][]mongo.IndexModel) (map[string][]string, error)
CreateIndexes creates multiple indexes across different collections in a single operation. This is useful for setting up database indexes during initialization or migrations.
Parameters:
- ctx: Context for cancellation and timeout control
- indexes: Map where keys are collection names and values are slices of IndexModel to create
Returns:
- map[string][]string: Map of collection names to slices of created index names
- error: Returns error if any index creation fails or client is closed
Note: If one index fails to create, subsequent indexes will not be attempted.
Example:
indexes := map[string][]mongo.IndexModel{
"users": {
{
Keys: bson.M{"email": 1},
Options: options.Index().SetUnique(true).SetName("unique_email"),
},
{
Keys: bson.D{{"country", 1}, {"city", 1}},
Options: options.Index().SetName("location_idx"),
},
},
"products": {
{
Keys: bson.M{"sku": 1},
Options: options.Index().SetUnique(true),
},
{
Keys: bson.M{"category": 1, "price": -1},
Options: options.Index().SetName("category_price_idx"),
},
},
}
createdIndexes, err := client.CreateIndexes(ctx, indexes)
if err != nil {
log.Fatal(err)
}
for collection, indexNames := range createdIndexes {
fmt.Printf("Collection '%s': created %d indexes\n", collection, len(indexNames))
}
func (*Client) DeleteMany ¶
func (c *Client) DeleteMany(ctx context.Context, collection string, filter any, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)
DeleteMany deletes all documents matching the filter.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to delete from
- filter: Query filter to match documents to delete. Can be bson.M, bson.D, or a struct. Use bson.M{} to delete all documents
- opts: Optional DeleteOptions for collation, hint, etc.
Returns:
- *mongo.DeleteResult: Contains DeletedCount with the number of documents deleted
- error: Returns error if operation fails or client is closed
Example:
filter := bson.M{"status": "inactive", "last_login": bson.M{"$lt": time.Now().AddDate(0, -6, 0)}}
result, err := client.DeleteMany(ctx, "users", filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %d inactive user(s)\n", result.DeletedCount)
func (*Client) DeleteOne ¶
func (c *Client) DeleteOne(ctx context.Context, collection string, filter any, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)
DeleteOne deletes a single document matching the filter.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to delete from
- filter: Query filter to match the document to delete. Can be bson.M, bson.D, or a struct
- opts: Optional DeleteOptions for collation, hint, etc.
Returns:
- *mongo.DeleteResult: Contains DeletedCount with the number of documents deleted (0 or 1)
- error: Returns error if operation fails or client is closed
Example:
filter := bson.M{"email": "user@example.com"}
result, err := client.DeleteOne(ctx, "users", filter)
if err != nil {
log.Fatal(err)
}
if result.DeletedCount == 0 {
fmt.Println("No document was deleted")
}
func (*Client) Distinct ¶
func (c *Client) Distinct(ctx context.Context, collection string, fieldName string, filter any, opts ...*options.DistinctOptions) ([]any, error)
Distinct gets all unique values for a specified field across documents matching the filter.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to query
- fieldName: The field name to get distinct values from (e.g., "country", "tags", "status")
- filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} for all documents
- opts: Optional DistinctOptions for collation, etc.
Returns:
- []any: Slice containing the distinct values found for the field
- error: Returns error if operation fails or client is closed
Example:
filter := bson.M{"status": "active"}
countries, err := client.Distinct(ctx, "users", "country", filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Active users are from %d different countries\n", len(countries))
for _, country := range countries {
fmt.Println(country)
}
func (*Client) DropIndex ¶
DropIndex removes an index from the specified collection.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to drop the index from
- indexName: Name of the index to drop (can be obtained from ListIndexes or when creating the index)
Returns:
- error: Returns error if operation fails, index doesn't exist, or client is closed
Example:
err := client.DropIndex(ctx, "users", "email_1")
if err != nil {
log.Fatal(err)
}
fmt.Println("Index dropped successfully")
func (*Client) Find ¶
func (c *Client) Find(ctx context.Context, collection string, filter any, results any, opts ...*options.FindOptions) error
Find finds all documents matching the filter and decodes them into results.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to search in
- filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} for all documents
- results: Pointer to a slice where found documents will be decoded (e.g., *[]User)
- opts: Optional FindOptions for sorting, projection, limit, skip, etc.
Returns:
- error: Returns error if operation fails or client is closed. Empty results is not an error
Example:
var users []User
filter := bson.M{"age": bson.M{"$gte": 18}}
opts := options.Find().SetLimit(10).SetSort(bson.M{"name": 1})
err := client.Find(ctx, "users", filter, &users, opts)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d users\n", len(users))
func (*Client) FindOne ¶
func (c *Client) FindOne(ctx context.Context, collection string, filter any, result any, opts ...*options.FindOneOptions) error
FindOne finds a single document matching the filter and decodes it into result.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to search in
- filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} for all documents
- result: Pointer to a variable where the found document will be decoded
- opts: Optional FindOneOptions for sorting, projection, skip, etc.
Returns:
- error: Returns ErrDocumentNotFound if no document matches, ErrClientClosed if client is closed, or operation error
Example:
var user User
err := client.FindOne(ctx, "users", bson.M{"email": "john@example.com"}, &user)
if err != nil {
if errors.Is(err, mongo.ErrDocumentNotFound) {
fmt.Println("User not found")
}
return err
}
fmt.Printf("Found user: %s\n", user.Name)
func (*Client) FindOneAndDelete ¶
func (c *Client) FindOneAndDelete(ctx context.Context, collection string, filter any, result any, opts ...*options.FindOneAndDeleteOptions) error
FindOneAndDelete finds a single document, deletes it, and returns the deleted document. This is an atomic operation that prevents race conditions.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to search and delete from
- filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
- result: Pointer to a variable where the deleted document will be decoded
- opts: Optional FindOneAndDeleteOptions for sorting, projection, collation, etc.
Returns:
- error: Returns ErrDocumentNotFound if no document matches, or operation error
Example:
var deletedUser User
filter := bson.M{"email": "tobedeleted@example.com"}
err := client.FindOneAndDelete(ctx, "users", filter, &deletedUser)
if err != nil {
if errors.Is(err, mongo.ErrDocumentNotFound) {
fmt.Println("User not found")
}
return err
}
fmt.Printf("Deleted user: %s\n", deletedUser.Name)
func (*Client) FindOneAndReplace ¶
func (c *Client) FindOneAndReplace(ctx context.Context, collection string, filter any, replacement any, result any, opts ...*options.FindOneAndReplaceOptions) error
FindOneAndReplace finds a single document, replaces it, and returns either the original or replaced document. This is an atomic operation that prevents race conditions.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to search and replace in
- filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
- replacement: The new document to replace with. Cannot contain update operators. The _id field will be preserved
- result: Pointer to a variable where the document will be decoded (original or replaced, depending on options)
- opts: Optional FindOneAndReplaceOptions. Use SetReturnDocument(options.After) to return the replaced document
Returns:
- error: Returns ErrDocumentNotFound if no document matches, or operation error
Example:
var oldUser User
filter := bson.M{"_id": userID}
newUser := User{Name: "Updated Name", Email: "new@example.com", Status: "active"}
opts := options.FindOneAndReplace().SetReturnDocument(options.Before)
err := client.FindOneAndReplace(ctx, "users", filter, newUser, &oldUser, opts)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Old user name: %s\n", oldUser.Name)
func (*Client) FindOneAndUpdate ¶
func (c *Client) FindOneAndUpdate(ctx context.Context, collection string, filter any, update any, result any, opts ...*options.FindOneAndUpdateOptions) error
FindOneAndUpdate finds a single document, updates it, and returns either the original or updated document. This is an atomic operation that prevents race conditions.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to search and update in
- filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
- update: Update operations to apply. Must use update operators like $set, $inc, etc.
- result: Pointer to a variable where the document will be decoded (original or updated, depending on options)
- opts: Optional FindOneAndUpdateOptions. Use SetReturnDocument(options.After) to return the updated document
Returns:
- error: Returns ErrDocumentNotFound if no document matches, or operation error
Example:
var user User
filter := bson.M{"email": "john@example.com"}
update := bson.M{"$inc": bson.M{"login_count": 1}, "$set": bson.M{"last_login": time.Now()}}
opts := options.FindOneAndUpdate().SetReturnDocument(options.After)
err := client.FindOneAndUpdate(ctx, "users", filter, update, &user, opts)
if err != nil {
log.Fatal(err)
}
fmt.Printf("User %s logged in %d times\n", user.Name, user.LoginCount)
func (*Client) GetCollection ¶
func (c *Client) GetCollection(collectionName string) *mongo.Collection
GetCollection returns a handle to the specified collection in the default database
func (*Client) GetCollectionFrom ¶
func (c *Client) GetCollectionFrom(databaseName, collectionName string) *mongo.Collection
GetCollectionFrom returns a handle to the specified collection in the specified database
func (*Client) GetDatabase ¶
GetDatabase returns a handle to the specified database If name is empty, returns the default database from config
func (*Client) InsertMany ¶
func (c *Client) InsertMany(ctx context.Context, collection string, documents []any) (*mongo.InsertManyResult, error)
InsertMany inserts multiple documents into the specified collection in a single operation.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection where documents will be inserted
- documents: Slice of documents to insert. Each element can be a struct, bson.M, bson.D, or any serializable type
Returns:
- *mongo.InsertManyResult: Contains InsertedIDs field with a map of insertion order to _id values
- error: Returns error if insertion fails or client is closed
Example:
users := []any{
User{Name: "John", Email: "john@example.com"},
User{Name: "Jane", Email: "jane@example.com"},
}
result, err := client.InsertMany(ctx, "users", users)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Inserted %d documents\n", len(result.InsertedIDs))
func (*Client) InsertOne ¶
func (c *Client) InsertOne(ctx context.Context, collection string, document any) (*mongo.InsertOneResult, error)
InsertOne inserts a single document into the specified collection.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection where the document will be inserted
- document: The document to insert. Can be a struct, bson.M, bson.D, or any serializable type
Returns:
- *mongo.InsertOneResult: Contains the InsertedID field with the _id of the inserted document
- error: Returns error if insertion fails or client is closed
Example:
type User struct {
Name string `bson:"name"`
Email string `bson:"email"`
}
result, err := client.InsertOne(ctx, "users", User{Name: "John", Email: "john@example.com"})
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted ID:", result.InsertedID)
func (*Client) IsConnected ¶
IsConnected checks if the client is connected to MongoDB
func (*Client) ListCollections ¶
ListCollections retrieves the names of all collections in the default database.
Parameters:
- ctx: Context for cancellation and timeout control
Returns:
- []string: Slice of collection names in the database
- error: Returns error if operation fails or client is closed
Example:
collections, err := client.ListCollections(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d collections:\n", len(collections))
for _, name := range collections {
fmt.Println("-", name)
}
func (*Client) ListDatabases ¶
ListDatabases lists all databases on the MongoDB server
func (*Client) ListIndexes ¶
ListIndexes retrieves information about all indexes on the specified collection.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to list indexes from
Returns:
- []bson.M: Slice of index specifications, each containing name, keys, unique, sparse, etc.
- error: Returns error if operation fails or client is closed
Example:
indexes, err := client.ListIndexes(ctx, "users")
if err != nil {
log.Fatal(err)
}
for _, index := range indexes {
fmt.Printf("Index: %s, Keys: %v\n", index["name"], index["key"])
}
func (*Client) Ping ¶
Ping verifies the connection to MongoDB Returns an error if connection verification fails
func (*Client) ReplaceOne ¶
func (c *Client) ReplaceOne(ctx context.Context, collection string, filter any, replacement any, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error)
ReplaceOne replaces a single document matching the filter with a new document. Unlike UpdateOne, this replaces the entire document (except _id) rather than modifying specific fields.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to replace in
- filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
- replacement: The new document to replace with. Cannot contain update operators like $set. The _id field will be preserved
- opts: Optional ReplaceOptions for upsert, bypass validation, etc.
Returns:
- *mongo.UpdateResult: Contains MatchedCount, ModifiedCount, UpsertedCount, and UpsertedID
- error: Returns error if operation fails or client is closed
Example:
filter := bson.M{"_id": userID}
newUser := User{Name: "John Doe", Email: "john@example.com", Age: 30}
result, err := client.ReplaceOne(ctx, "users", filter, newUser)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Replaced %d document(s)\n", result.ModifiedCount)
func (*Client) StartSession ¶
StartSession starts a new session for transaction support
func (*Client) UpdateMany ¶
func (c *Client) UpdateMany(ctx context.Context, collection string, filter any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)
UpdateMany updates all documents matching the filter.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to update in
- filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} to update all documents
- update: Update operations to apply. Must use update operators like $set, $inc, etc. (e.g., bson.M{"$set": bson.M{"status": "active"}})
- opts: Optional UpdateOptions for upsert, bypass validation, etc.
Returns:
- *mongo.UpdateResult: Contains MatchedCount, ModifiedCount, UpsertedCount, and UpsertedID
- error: Returns error if operation fails or client is closed
Example:
filter := bson.M{"status": "pending"}
update := bson.M{"$set": bson.M{"status": "processed", "processed_at": time.Now()}}
result, err := client.UpdateMany(ctx, "orders", filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Modified %d document(s)\n", result.ModifiedCount)
func (*Client) UpdateOne ¶
func (c *Client) UpdateOne(ctx context.Context, collection string, filter any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)
UpdateOne updates a single document matching the filter.
Parameters:
- ctx: Context for cancellation and timeout control
- collection: Name of the collection to update in
- filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
- update: Update operations to apply. Must use update operators like $set, $inc, etc. (e.g., bson.M{"$set": bson.M{"age": 30}})
- opts: Optional UpdateOptions for upsert, bypass validation, etc.
Returns:
- *mongo.UpdateResult: Contains MatchedCount, ModifiedCount, UpsertedCount, and UpsertedID
- error: Returns error if operation fails or client is closed
Example:
filter := bson.M{"email": "john@example.com"}
update := bson.M{"$set": bson.M{"age": 31}, "$inc": bson.M{"login_count": 1}}
result, err := client.UpdateOne(ctx, "users", filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Modified %d document(s)\n", result.ModifiedCount)
func (*Client) UseSession ¶
UseSession executes a function within a session
type CountOptions ¶
type CountOptions = options.CountOptions
CountOptions is a convenient alias for options.CountOptions
type CreateCollectionOptions ¶
type CreateCollectionOptions = options.CreateCollectionOptions
CreateCollectionOptions is a convenient alias for options.CreateCollectionOptions
type DeleteOptions ¶
type DeleteOptions = options.DeleteOptions
DeleteOptions is a convenient alias for options.DeleteOptions
type DistinctOptions ¶
type DistinctOptions = options.DistinctOptions
DistinctOptions is a convenient alias for options.DistinctOptions
type FindOneAndDeleteOptions ¶
type FindOneAndDeleteOptions = options.FindOneAndDeleteOptions
FindOneAndDeleteOptions is a convenient alias for options.FindOneAndDeleteOptions
type FindOneAndReplaceOptions ¶
type FindOneAndReplaceOptions = options.FindOneAndReplaceOptions
FindOneAndReplaceOptions is a convenient alias for options.FindOneAndReplaceOptions
type FindOneAndUpdateOptions ¶
type FindOneAndUpdateOptions = options.FindOneAndUpdateOptions
FindOneAndUpdateOptions is a convenient alias for options.FindOneAndUpdateOptions
type FindOneOptions ¶
type FindOneOptions = options.FindOneOptions
FindOneOptions is a convenient alias for options.FindOneOptions
type FindOptions ¶
type FindOptions = options.FindOptions
FindOptions is a convenient alias for options.FindOptions
type IndexOptions ¶
type IndexOptions = options.IndexOptions
IndexOptions is a convenient alias for options.IndexOptions
type InsertManyOptions ¶
type InsertManyOptions = options.InsertManyOptions
InsertManyOptions is a convenient alias for options.InsertManyOptions
type InsertOneOptions ¶
type InsertOneOptions = options.InsertOneOptions
InsertOneOptions is a convenient alias for options.InsertOneOptions
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder provides a fluent interface for building MongoDB queries
func NewQueryBuilder ¶
func NewQueryBuilder() *QueryBuilder
NewQueryBuilder creates a new QueryBuilder instance
func (*QueryBuilder) And ¶
func (qb *QueryBuilder) And(conditions ...bson.D) *QueryBuilder
And adds an and condition
func (*QueryBuilder) Build ¶
func (qb *QueryBuilder) Build() (bson.D, *options.FindOptions)
Build returns the filter and options
func (*QueryBuilder) BuildFilter ¶
func (qb *QueryBuilder) BuildFilter() bson.D
BuildFilter returns only the filter
func (*QueryBuilder) BuildOptions ¶
func (qb *QueryBuilder) BuildOptions() *options.FindOptions
BuildOptions returns only the options
func (*QueryBuilder) Equals ¶
func (qb *QueryBuilder) Equals(key string, value interface{}) *QueryBuilder
Equals adds an equality filter
func (*QueryBuilder) Exists ¶
func (qb *QueryBuilder) Exists(key string, exists bool) *QueryBuilder
Exists adds an exists filter
func (*QueryBuilder) Filter ¶
func (qb *QueryBuilder) Filter(key string, value interface{}) *QueryBuilder
Filter adds a filter condition to the query
func (*QueryBuilder) GreaterThan ¶
func (qb *QueryBuilder) GreaterThan(key string, value interface{}) *QueryBuilder
GreaterThan adds a greater than filter
func (*QueryBuilder) GreaterThanOrEqual ¶
func (qb *QueryBuilder) GreaterThanOrEqual(key string, value interface{}) *QueryBuilder
GreaterThanOrEqual adds a greater than or equal filter
func (*QueryBuilder) In ¶
func (qb *QueryBuilder) In(key string, values ...interface{}) *QueryBuilder
In adds an in filter
func (*QueryBuilder) LessThan ¶
func (qb *QueryBuilder) LessThan(key string, value interface{}) *QueryBuilder
LessThan adds a less than filter
func (*QueryBuilder) LessThanOrEqual ¶
func (qb *QueryBuilder) LessThanOrEqual(key string, value interface{}) *QueryBuilder
LessThanOrEqual adds a less than or equal filter
func (*QueryBuilder) Limit ¶
func (qb *QueryBuilder) Limit(limit int64) *QueryBuilder
Limit sets the maximum number of documents to return
func (*QueryBuilder) Nor ¶
func (qb *QueryBuilder) Nor(conditions ...bson.D) *QueryBuilder
Nor adds a nor condition
func (*QueryBuilder) NotEquals ¶
func (qb *QueryBuilder) NotEquals(key string, value interface{}) *QueryBuilder
NotEquals adds a not equals filter
func (*QueryBuilder) NotIn ¶
func (qb *QueryBuilder) NotIn(key string, values ...interface{}) *QueryBuilder
NotIn adds a not in filter
func (*QueryBuilder) Or ¶
func (qb *QueryBuilder) Or(conditions ...bson.D) *QueryBuilder
Or adds an or condition
func (*QueryBuilder) Project ¶
func (qb *QueryBuilder) Project(projection interface{}) *QueryBuilder
Project sets the projection
func (*QueryBuilder) Regex ¶
func (qb *QueryBuilder) Regex(key string, pattern string, options string) *QueryBuilder
Regex adds a regex filter
func (*QueryBuilder) Skip ¶
func (qb *QueryBuilder) Skip(skip int64) *QueryBuilder
Skip sets the number of documents to skip
func (*QueryBuilder) Sort ¶
func (qb *QueryBuilder) Sort(field string, ascending bool) *QueryBuilder
Sort sets the sort order
func (*QueryBuilder) SortBy ¶
func (qb *QueryBuilder) SortBy(sort interface{}) *QueryBuilder
SortBy sets custom sort order
type ReplaceOptions ¶
type ReplaceOptions = options.ReplaceOptions
ReplaceOptions is a convenient alias for options.ReplaceOptions
type UpdateBuilder ¶
type UpdateBuilder struct {
// contains filtered or unexported fields
}
UpdateBuilder provides a fluent interface for building update operations
func NewUpdateBuilder ¶
func NewUpdateBuilder() *UpdateBuilder
NewUpdateBuilder creates a new UpdateBuilder instance
func (*UpdateBuilder) AddToSet ¶
func (ub *UpdateBuilder) AddToSet(key string, value interface{}) *UpdateBuilder
AddToSet adds value to array if not already present
func (*UpdateBuilder) Build ¶
func (ub *UpdateBuilder) Build() bson.D
Build returns the update document
func (*UpdateBuilder) CurrentDate ¶
func (ub *UpdateBuilder) CurrentDate(key string) *UpdateBuilder
CurrentDate sets field to current date
func (*UpdateBuilder) Inc ¶
func (ub *UpdateBuilder) Inc(key string, value interface{}) *UpdateBuilder
Inc increments field values
func (*UpdateBuilder) Max ¶
func (ub *UpdateBuilder) Max(key string, value interface{}) *UpdateBuilder
Max updates field if specified value is greater than current value
func (*UpdateBuilder) Min ¶
func (ub *UpdateBuilder) Min(key string, value interface{}) *UpdateBuilder
Min updates field if specified value is less than current value
func (*UpdateBuilder) Mul ¶
func (ub *UpdateBuilder) Mul(key string, value interface{}) *UpdateBuilder
Mul multiplies field values
func (*UpdateBuilder) Pop ¶
func (ub *UpdateBuilder) Pop(key string, first bool) *UpdateBuilder
Pop removes first or last element from array
func (*UpdateBuilder) Pull ¶
func (ub *UpdateBuilder) Pull(key string, value interface{}) *UpdateBuilder
Pull removes all instances of value from array
func (*UpdateBuilder) Push ¶
func (ub *UpdateBuilder) Push(key string, value interface{}) *UpdateBuilder
Push appends value to array
func (*UpdateBuilder) Rename ¶
func (ub *UpdateBuilder) Rename(oldName string, newName string) *UpdateBuilder
Rename renames a field
func (*UpdateBuilder) Set ¶
func (ub *UpdateBuilder) Set(key string, value interface{}) *UpdateBuilder
Set sets field values
func (*UpdateBuilder) SetMultiple ¶
func (ub *UpdateBuilder) SetMultiple(fields map[string]interface{}) *UpdateBuilder
SetMultiple sets multiple field values at once
func (*UpdateBuilder) Unset ¶
func (ub *UpdateBuilder) Unset(keys ...string) *UpdateBuilder
Unset removes fields
type UpdateOptions ¶
type UpdateOptions = options.UpdateOptions
UpdateOptions is a convenient alias for options.UpdateOptions
type WriteModel ¶
type WriteModel = mongo.WriteModel
WriteModel is an interface for bulk write operations