### Install mongox Go Package Source: https://github.com/maxbolgarin/mongox/blob/main/README.md This command installs the mongox package and its dependencies using the Go build tool. Ensure you have Go installed and configured correctly. ```bash go get -u github.com/maxbolgarin/mongox ``` -------------------------------- ### Manage database indexes and text search with Mongox Source: https://context7.com/maxbolgarin/mongox/llms.txt Explains how to create unique, compound, and text indexes to improve query efficiency. Includes an example of executing a full-text search query using the created text index. ```go package main import ( "context" "log" "github.com/maxbolgarin/mongox" ) func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") // Create a unique index on email field err := users.CreateIndex(ctx, true, "email") if err != nil { log.Fatalf("Failed to create unique index: %v", err) } log.Println("Unique index on email created") // Create a compound index on multiple fields (non-unique) err = users.CreateIndex(ctx, false, "age", "created_at") if err != nil { log.Fatalf("Failed to create compound index: %v", err) } log.Println("Compound index created") // Create a text index for full-text search err = users.CreateTextIndex(ctx, "en", "name", "bio", "interests") if err != nil { log.Fatalf("Failed to create text index: %v", err) } log.Println("Text index created for English language") // Now you can perform text searches var results []struct { Name string `bson:"name"` Bio string `bson:"bio"` } err = users.Find(ctx, &results, mongox.M{ mongox.Text: mongox.M{"$search": "developer golang"}, }) if err != nil { log.Fatalf("Text search failed: %v", err) } log.Printf("Found %d users matching text search", len(results)) } ``` -------------------------------- ### Manage MongoDB Indexes using mongox in Go Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Explains how to create indexes in MongoDB for performance optimization using mongox. It shows examples for creating unique indexes and text indexes. ```go // Create a unique index on the 'email' field err := collection.CreateIndex(ctx, true, "email") if err != nil { return err } // Create a text index for text search on 'name' and 'bio' fields err = collection.CreateTextIndex(ctx, "en", "name", "bio") if err != nil { return err } ``` -------------------------------- ### Manage retry-exhausted tasks and statistics collection Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Demonstrates how to start a background monitor for tasks that have exhausted retries and how to disable statistics collection for performance optimization. ```go // Start background monitoring for retry-exhausted errors asyncDB.StartRetryExhaustedMonitor(ctx, 5*time.Second) // Disable statistics collection asyncDB := client.AsyncDatabase(ctx, "mydb", 10, logger).WithNoAsyncStats() ``` -------------------------------- ### Perform Async Database Operations with Retries in Go Source: https://context7.com/maxbolgarin/mongox/llms.txt Illustrates how to use mongox's asynchronous database client for executing operations concurrently using worker pools. It features automatic retry logic for transient errors, custom error handling, and task management. The example shows setting up an async database, defining queues, and monitoring error statistics. ```go package main import ( "context" "errors" "log" "time" "github.com/maxbolgarin/mongox" ) type SimpleLogger struct{} func (l SimpleLogger) Debug(msg string, args ...any) { log.Printf("[DEBUG] "+msg, args...) } func (l SimpleLogger) Info(msg string, args ...any) { log.Printf("[INFO] "+msg, args...) } func (l SimpleLogger) Error(msg string, args ...any) { log.Printf("[ERROR] "+msg, args...) } type User struct { Name string `bson:"name" Email string `bson:"email" } func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) logger := SimpleLogger{} // Create async database with 10 worker goroutines asyncDB := client.AsyncDatabase(ctx, "mydb", 10, logger) // Set up error handler for monitoring asyncDB.WithErrorHandler(func(err *mongox.AsyncError) { log.Printf("Async error in %s.%s [%s]: %v", err.Collection, err.Operation, err.TaskName, err.Err) if errors.Is(err.Err, mongox.ErrDuplicate) { log.Printf("Duplicate key detected, handle accordingly") } if !err.IsNotRetryable { log.Printf("Task %s exhausted %d retries", err.TaskName, err.RetryCount) } }) // Get async collection users := asyncDB.AsyncCollection("users") // Fire-and-forget insert (operations in same queue execute sequentially) users.Insert("user_queue", "create_alice", User{Name: "Alice", Email: "alice@example.com"}) users.Insert("user_queue", "create_bob", User{Name: "Bob", Email: "bob@example.com"}) // Operations in different queues execute in parallel users.UpdateOne("updates_queue", "update_age", mongox.M{"name": "Alice"}, mongox.M{mongox.Inc: mongox.M{"age": 1}}, ) users.SetFields("updates_queue", "verify_user", mongox.M{"name": "Bob"}, mongox.M{"verified": true}, ) // Delete operation users.DeleteOne("cleanup_queue", "remove_old", mongox.M{"active": false}) // Check queue statistics time.Sleep(100 * time.Millisecond) stats := asyncDB.ErrorStats() log.Printf("Total errors: %d, Non-retryable: %d, Retry-exhausted: %d", stats.TotalErrors, stats.NonRetryableErrors, stats.RetryExhaustedErrors) // Start retry-exhausted monitor monitorCtx, cancel := context.WithCancel(ctx) asyncDB.StartRetryExhaustedMonitor(monitorCtx, 5*time.Second) defer cancel() // Execute custom async task asyncDB.WithTask("custom_queue", "complex_operation", func(ctx context.Context) error { // Perform complex database operations return nil }) time.Sleep(time.Second) // Wait for operations to complete } ``` -------------------------------- ### Go: Find Documents with Filters, Sorting, and Pagination Source: https://context7.com/maxbolgarin/mongox/llms.txt Demonstrates how to find single and multiple documents from a MongoDB collection using the mongox library. It includes examples of using filters with comparison operators (gte, lt), sorting results by age in ascending order, limiting the number of documents returned, and skipping documents. It also shows how to use type-safe generic functions for finding documents and retrieving all documents in a collection. ```go package main import ( "context" "log" "github.com/maxbolgarin/mongox" ) type User struct { Name string `bson:"name"` Email string `bson:"email"` Age int `bson:"age"` } func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") // Find one document with filter var user User err := users.FindOne(ctx, &user, mongox.M{"email": "alice@example.com"}) if err != nil { if err == mongox.ErrNotFound { log.Println("User not found") } else { log.Fatalf("Find failed: %v", err) } } log.Printf("Found user: %s, age: %d", user.Name, user.Age) // Find multiple documents with comparison operators filter := mongox.M{"age": mongox.M{mongox.Gte: 25, mongox.Lt: 40}} var userList []User err = users.Find(ctx, &userList, filter, mongox.FindOptions{ Sort: mongox.M{"age": mongox.Ascending}, Limit: 10, Skip: 0, }) if err != nil { log.Fatalf("Find many failed: %v", err) } log.Printf("Found %d users aged 25-39", len(userList)) // Using generic function (no pointer needed) result, err := mongox.FindOne[User](ctx, users, mongox.M{"name": "Bob"}) if err != nil { log.Fatalf("Generic find failed: %v", err) } log.Printf("Found user via generic: %s", result.Name) // Find all documents in collection allUsers, err := mongox.FindAll[User](ctx, users, mongox.FindOptions{ Limit: 100, }) if err != nil { log.Fatalf("Find all failed: %v", err) } log.Printf("Total users: %d", len(allUsers)) } ``` -------------------------------- ### Insert Documents into MongoDB using MongoX in Go Source: https://context7.com/maxbolgarin/mongox/llms.txt Illustrates how to insert single and multiple documents into a MongoDB collection using the MongoX library. It showcases both the collection-specific `InsertOne` and `Insert` methods, as well as a generic `mongox.InsertOne` function for type-safe operations. The code includes examples of automatic ObjectID generation and error handling. ```go package main import ( "context" "log" "github.com/maxbolgarin/mongox" ) type User struct { ID string `bson:"_id,omitempty"` Name string `bson:"name"` Email string `bson:"email"` Age int `bson:"age"` } func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") // Insert a single document user := User{Name: "Alice", Email: "alice@example.com", Age: 30} id, err := users.InsertOne(ctx, user) if err != nil { log.Fatalf("Insert failed: %v", err) } log.Printf("Inserted user with ID: %s", id.Hex()) // Insert multiple documents using variadic syntax ids, err := users.Insert(ctx, User{Name: "Bob", Email: "bob@example.com", Age: 25}, User{Name: "Charlie", Email: "charlie@example.com", Age: 35}, ) if err != nil { log.Fatalf("Bulk insert failed: %v", err) } log.Printf("Inserted %d users", len(ids)) // Using generic function for type safety id, err = mongox.InsertOne(ctx, users, User{Name: "Diana", Email: "diana@example.com", Age: 28}) if err != nil { log.Fatalf("Generic insert failed: %v", err) } log.Printf("Inserted with generic function, ID: %s", id.Hex()) } ``` -------------------------------- ### Update Documents in MongoDB using mongox in Go Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Provides examples of updating documents in a MongoDB collection. It covers updating single documents, incrementing fields, setting new fields, and performing upserts. ```go type M = mongox.M update := M{ mongox.Inc: M{ "age": 1, }, } // Update a single document err := collection.UpdateOne(ctx, filter, update) if err != nil { return err } // Set new fields err := collection.SetFields(ctx, filter, M{"new_field": "value"}) if err != nil { return err } // Upsert a document (update or insert) record := User{ Name: "Diana", Age: 28, } _, err = collection.Upsert(ctx, record, M{"name": "Alice"}) if err != nil { return err } ``` -------------------------------- ### Delete Documents from MongoDB using mongox in Go Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Demonstrates how to delete documents from a MongoDB collection. It includes examples for deleting a single document and deleting multiple documents based on a filter. ```go // Delete a single document err := collection.DeleteOne(ctx, M{"name": "Diana"}) if err != nil { return err } // Delete multiple documents n, err = collection.DeleteMany(ctx, M{"age": mongox.Lt(30)}) if err != nil { return err } ``` -------------------------------- ### Go: Update Documents with Operators and Upsert Source: https://context7.com/maxbolgarin/mongox/llms.txt Illustrates how to update documents in a MongoDB collection using the mongox library. It covers updating a single document with operators like $set and $inc, using the SetFields helper for convenience, and updating multiple documents based on a filter. The example also demonstrates the upsert functionality, which updates an existing document or inserts a new one if no match is found. ```go package main import ( "context" "log" "github.com/maxbolgarin/mongox" ) type M = mongox.M // Type alias for cleaner code func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") // Update one document using $set operator filter := M{"email": "alice@example.com"} update := M{ mongox.Set: M{"age": 31, "updated": true}, mongox.Inc: M{"login_count": 1}, } err := users.UpdateOne(ctx, filter, update) if err != nil { if err == mongox.ErrNotFound { log.Println("No document matched the filter") } else { log.Fatalf("Update failed: %v", err) } } log.Println("Document updated successfully") // SetFields helper - automatically wraps in $set err = users.SetFields(ctx, M{"name": "Bob"}, M{ "email": "bob.new@example.com", "verified": true, }) if err != nil { log.Fatalf("SetFields failed: %v", err) } // Update many documents count, err := users.UpdateMany(ctx, M{"age": M{mongox.Lt: 30}}, M{mongox.Set: M{"category": "young"}}, ) if err != nil { log.Fatalf("UpdateMany failed: %v", err) } log.Printf("Updated %d documents", count) // Upsert - update or insert if not exists newUser := struct { Name string `bson:"name"` Email string `bson:"email"` Age int `bson:"age"` }{Name: "Eve", Email: "eve@example.com", Age: 22} id, err := users.Upsert(ctx, newUser, M{"email": "eve@example.com"}) if err != nil { log.Fatalf("Upsert failed: %v", err) } if id != nil { log.Printf("Inserted new document with ID: %s", id.Hex()) } else { log.Println("Updated existing document") } } ``` -------------------------------- ### Initialize mongox Client and Collection in Go Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Demonstrates how to initialize a mongox client with configuration and obtain a database collection. It includes setting up connection details, authentication, and deferring client disconnection. ```go cfg := mongox.Config{ AppName: "MyApp", Address: "localhost:27017", Auth: &mongox.AuthConfig{ Username: "username", Password: "password", }, // TODO: other settings } client, err := mongox.Connect(ctx, cfg) if err != nil { return err } defer client.Disconnect(ctx) // TODO: handle error db := client.Database("mydb") collection := db.Collection("users") ``` -------------------------------- ### Connect to MongoDB using MongoX in Go Source: https://context7.com/maxbolgarin/mongox/llms.txt Demonstrates how to establish a connection to a MongoDB instance using the MongoX library. It covers basic configuration options such as application name, address, authentication, and connection pooling. The function returns a client instance and handles potential connection errors. ```go package main import ( "context" "log" "time" "github.com/maxbolgarin/mongox" ) func main() { ctx := context.Background() // Basic connection configuration cfg := mongox.Config{ AppName: "MyApp", Address: "localhost:27017", Auth: &mongox.AuthConfig{ Username: "admin", Password: "password", AuthSource: "admin", }, Connection: &mongox.ConnectionConfig{ ConnectTimeout: durationPtr(30 * time.Second), MaxPoolSize: uint64Ptr(100), MinPoolSize: uint64Ptr(10), }, } // Connect to MongoDB client, err := mongox.Connect(ctx, cfg) if err != nil { log.Fatalf("Failed to connect: %v", err) } defer client.Disconnect(ctx) // Verify connection if err := client.Ping(ctx); err != nil { log.Fatalf("Failed to ping: %v", err) } // Get database and collection db := client.Database("mydb") users := db.Collection("users") log.Printf("Connected to collection: %s", users.Name()) } func durationPtr(d time.Duration) *time.Duration { return &d } func uint64Ptr(n uint64) *uint64 { return &n } ``` -------------------------------- ### Execute asynchronous operations with mongox Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Shows how to initialize an AsyncDatabase and perform asynchronous document insertions. Operations with the same queue name are executed sequentially, while different queues run in parallel. ```go asyncDB := client.AsyncDatabase(ctx, "mydb", 10, logger) // 10 workers asyncCollection := asyncDB.AsyncCollection("users") // Insert a document asynchronously asyncCollection.Insert("users_queue", "insert_task", User{ Name: "Alice", Age: 30, }) ``` -------------------------------- ### Find Documents in MongoDB using mongox in Go Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Illustrates how to query documents from a MongoDB collection. It demonstrates finding multiple documents with a filter and finding a single document with sorting options using generic methods. ```go // Define a filter filter := mongox.M{"age": mongox.Gt(20)} // Find multiple documents var users []mongox.User err = collection.Find(ctx, &users, filter) if err != nil { return err } // Find a one document with a generic method and applied sort result, err := mongox.FindOne[User](ctx, collection, filter, mongox.FindOptions{ Sort: mongox.M{"age": 1}, }) if err != nil { return err } ``` -------------------------------- ### Execute Bulk Write Operations in Go Source: https://context7.com/maxbolgarin/mongox/llms.txt Demonstrates how to use mongox.NewBulkBuilder to group multiple write operations (insert, update, upsert, delete, set fields) into a single database round trip. This enhances efficiency by reducing network latency. The code includes error handling for the bulk write result. ```go package main import ( "context" "log" "github.com/maxbolgarin/mongox" ) type User struct { Name string `bson:"name" Email string `bson:"email" Age int `bson:"age" } func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") // Create a bulk builder bulk := mongox.NewBulkBuilder() // Add insert operations bulk.Insert( User{Name: "Alice", Email: "alice@example.com", Age: 30}, User{Name: "Bob", Email: "bob@example.com", Age: 25}, ) // Add update operation bulk.UpdateOne( mongox.M{"email": "charlie@example.com"}, mongox.M{mongox.Set: mongox.M{"age": 36}}, ) // Add upsert operation bulk.Upsert( User{Name: "Diana", Email: "diana@example.com", Age: 28}, mongox.M{"email": "diana@example.com"}, ) // Add delete operation bulk.DeleteOne(mongox.M{"name": "OldUser"}) // Add SetFields operation bulk.SetFields( mongox.M{"email": "eve@example.com"}, mongox.M{"verified": true, "updated_at": "2024-01-01"}, ) // Execute bulk write (ordered = true means stop on first error) result, err := users.BulkWrite(ctx, bulk.Models(), true) if err != nil { log.Fatalf("Bulk write failed: %v", err) } log.Printf("Bulk operation results:") log.Printf(" Inserted: %d", result.InsertedCount) log.Printf(" Modified: %d", result.ModifiedCount) log.Printf(" Deleted: %d", result.DeletedCount) log.Printf(" Upserted: %d", result.UpsertedCount) } ``` -------------------------------- ### Insert Documents into MongoDB using mongox in Go Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Shows how to insert single or multiple documents into a MongoDB collection using the mongox library. It covers direct insertion and using a generic insert method. ```go type User struct { Name string `bson:"name"` Age int `bson:"age"` } user := User{Name: "Alice", Age: 30} // Insert a single document _, err := collection.Insert(ctx, user) if err != nil { return err } // Insert multiple documents _, err = collection.Insert(ctx, User{Name: "Bob", Age: 30}, User{Name: "Charlie", Age: 35}, ) if err != nil { return err } // Insert with generic method _, err = mongox.Insert(ctx, collection, User{Name: "Mike", Age: 20}) if err != nil { return err } ``` -------------------------------- ### Implement MongoDB Query and Update Operators in Go Source: https://context7.com/maxbolgarin/mongox/llms.txt Demonstrates the usage of MongoX constants for various MongoDB operations including comparison, logical, array, and update operators. These constants replace raw strings to ensure type safety and reduce syntax errors when building complex queries. ```go package main import ( "context" "log" "github.com/maxbolgarin/mongox" ) type M = mongox.M func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") var results []map[string]any // Comparison operators users.Find(ctx, &results, M{"age": M{mongox.Gte: 18, mongox.Lt: 65}}) users.Find(ctx, &results, M{"status": M{mongox.In: []string{"active", "pending"}}}) // Logical operators users.Find(ctx, &results, M{ mongox.And: []M{ {"age": M{mongox.Gte: 21}}, {"verified": true}, }, }) // Update operators users.UpdateOne(ctx, M{"_id": "user123"}, M{ mongox.Set: M{"name": "New Name"}, mongox.Inc: M{"login_count": 1}, mongox.Push: M{"login_history": "2024-01-01"}, }, ) log.Println("Operator examples completed") } ``` -------------------------------- ### Execute Atomic MongoDB Transactions in Go Source: https://context7.com/maxbolgarin/mongox/llms.txt Demonstrates how to perform multiple MongoDB operations atomically using MongoX transactions. This requires a replica set or sharded cluster. It includes debiting from one account and crediting another within a single transaction. ```go package main import ( "context" "fmt" "log" "github.com/maxbolgarin/mongox" ) type Account struct { ID string `bson:"_id"` Owner string `bson:"owner"` Balance float64 `bson:"balance"` } func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{ Address: "localhost:27017", ReplicaSetName: "rs0", // Transactions require replica set }) defer client.Disconnect(ctx) db := client.Database("bank") // Execute a transaction for money transfer result, err := db.WithTransaction(ctx, func(txCtx context.Context) (any, error) { accounts := db.Collection("accounts") // Debit from source account err := accounts.UpdateOne(txCtx, mongox.M{"_id": "account_a", "balance": mongox.M{mongox.Gte: 100.0}}, mongox.M{mongox.Inc: mongox.M{"balance": -100.0}}, ) if err != nil { return nil, fmt.Errorf("failed to debit: %w", err) } // Credit to destination account err = accounts.UpdateOne(txCtx, mongox.M{"_id": "account_b"}, mongox.M{mongox.Inc: mongox.M{"balance": 100.0}}, ) if err != nil { return nil, fmt.Errorf("failed to credit: %w", err) } return "transfer_completed", nil }) if err != nil { log.Fatalf("Transaction failed: %v", err) } log.Printf("Transaction result: %v", result) } ``` -------------------------------- ### Handle MongoDB Errors with Typed Errors in Go Source: https://context7.com/maxbolgarin/mongox/llms.txt Illustrates how to use MongoX's typed errors for precise error handling and recovery. It shows how to check for specific error types like duplicate keys, not found, or network issues after performing database operations. ```go package main import ( "context" "errors" "log" "github.com/maxbolgarin/mongox" ) func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") // Create unique index users.CreateIndex(ctx, true, "email") // Insert document _, err := users.Insert(ctx, map[string]any{"name": "Alice", "email": "alice@example.com"}) // Try to insert duplicate _, err = users.Insert(ctx, map[string]any{"name": "Alice2", "email": "alice@example.com"}) if err != nil { switch { case errors.Is(err, mongox.ErrDuplicate): log.Println("Duplicate email address - user already exists") case errors.Is(err, mongox.ErrNotFound): log.Println("Document not found") case errors.Is(err, mongox.ErrInvalidArgument): log.Println("Invalid argument provided to operation") case errors.Is(err, mongox.ErrNetwork): log.Println("Network error - check MongoDB connection") case errors.Is(err, mongox.ErrTimeout): log.Println("Operation timed out") case errors.Is(err, mongox.ErrUnauthorized): log.Println("Authentication failed - check credentials") case errors.Is(err, mongox.ErrBadValue): log.Println("Bad value in query or update") case errors.Is(err, mongox.ErrIndexNotFound): log.Println("Referenced index does not exist") default: log.Printf("Other error: %v", err) } } // Find non-existent document var user map[string]any err = users.FindOne(ctx, &user, mongox.M{"email": "nonexistent@example.com"}) if errors.Is(err, mongox.ErrNotFound) { log.Println("User not found - handle gracefully") } } ``` -------------------------------- ### Handle synchronous errors in mongox Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Demonstrates how to handle specific errors returned by synchronous collection operations using standard Go error wrapping and the errors.Is function. ```go err := collection.Insert(ctx, User{ Name: eveName, Age: eveAge, }) if err != nil { if errors.Is(err, mongox.ErrNotFound) { // Handle not found } else if errors.Is(err, mongox.ErrInvalidArgument) { // Handle invalid argument } else { // Handle other errors } } ``` -------------------------------- ### Monitor and manage error statistics Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Provides methods to retrieve, display, and reset error statistics for asynchronous operations, including collection and operation-level breakdowns. ```go // Get current statistics snapshot stats := asyncDB.ErrorStats() fmt.Printf("Total errors: %d\n", stats.TotalErrors) fmt.Printf("Non-retryable: %d\n", stats.NonRetryableErrors) fmt.Printf("Retry-exhausted: %d\n", stats.RetryExhaustedErrors) // Statistics by collection for coll, s := range stats.ByCollection { fmt.Printf("Collection %s: %d errors\n", coll, s.Total) } // Reset statistics asyncDB.ResetErrorStats() ``` -------------------------------- ### Configure asynchronous error handling Source: https://github.com/maxbolgarin/mongox/blob/main/README.md Configures a global error handler for asynchronous operations to process errors, check retry status, and perform alerting based on error types. ```go asyncDB := client.AsyncDatabase(ctx, "mydb", 10, logger) // Set up error handler to receive all async errors asyncDB.WithErrorHandler(func(err *mongox.AsyncError) { log.Printf("Async error in %s.%s: %v", err.Collection, err.Operation, err.Err) if errors.Is(err.Err, mongox.ErrDuplicate) { alerting.Send("Duplicate key in " + err.Collection) } if !err.IsNotRetryable { log.Printf("Task %s exhausted all %d retries", err.TaskName, err.RetryCount) } }) ``` -------------------------------- ### Perform document deletion operations with Mongox Source: https://context7.com/maxbolgarin/mongox/llms.txt Demonstrates how to remove documents from a MongoDB collection using single, bulk, and atomic deletion methods. It also covers the removal of specific fields from existing documents. ```go package main import ( "context" "log" "github.com/maxbolgarin/mongox" ) func main() { ctx := context.Background() client, _ := mongox.Connect(ctx, mongox.Config{Address: "localhost:27017"}) defer client.Disconnect(ctx) users := client.Database("mydb").Collection("users") // Delete a single document err := users.DeleteOne(ctx, mongox.M{"email": "alice@example.com"}) if err != nil { if err == mongox.ErrNotFound { log.Println("No document to delete") } else { log.Fatalf("Delete failed: %v", err) } } log.Println("User deleted") // Delete multiple documents count, err := users.DeleteMany(ctx, mongox.M{"age": mongox.M{mongox.Lt: 18}}) if err != nil { log.Fatalf("DeleteMany failed: %v", err) } log.Printf("Deleted %d underage users", count) // Find and delete atomically var deletedUser struct { Name string `bson:"name"` Age int `bson:"age"` } err = users.FindOneAndDelete(ctx, &deletedUser, mongox.M{"name": "Bob"}) if err != nil { log.Fatalf("FindOneAndDelete failed: %v", err) } log.Printf("Deleted user: %s, age: %d", deletedUser.Name, deletedUser.Age) // Delete specific fields from a document err = users.DeleteFields(ctx, mongox.M{"name": "Charlie"}, "temporary_token", "session_data") if err != nil { log.Fatalf("DeleteFields failed: %v", err) } log.Println("Fields removed from document") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.