### ForEach Cursor Examples Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Examples demonstrating the use of `forEach` to process each element, including handling transformation errors. ```swift try await users.find().forEach { user in print("Processing user: \(user[\"name\"])") } // With error handling for transformations try await users.find().decode(User.self).forEach(failable: true) { user in print("Processing user: \(user.name)") } ``` -------------------------------- ### Decode Cursor Examples Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Examples demonstrating how to decode documents into a `User` struct, including using a custom `BSONDecoder` with a different date strategy. ```swift struct User: Codable { let id: ObjectId let name: String let email: String } let adults = try await users.find("age" >= 18) .decode(User.self) .drain() // Using a custom decoder let decoder = BSONDecoder() decoder.dateDecodingStrategy = .millisecondsSince1970 let results = try await users.find() .decode(User.self, using: decoder) .drain() ``` -------------------------------- ### Map Cursor Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Example demonstrating how to use the `map` function to extract and transform specific fields from documents. ```swift let userAges = users.find().map { doc["age"] as Int? ?? 0 } ``` -------------------------------- ### Quick Start with MongoKitten Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Demonstrates basic connection, document insertion, querying, and Codable decoding. ```swift // Add to Package.swift .package(url: "https://github.com/orlandos-nl/MongoKitten.git", from: "7.9.0") // In your code import MongoKitten // Connect to database let db = try await MongoDatabase.connect(to: "mongodb://localhost/my_database") // Insert a document try await db["users"].insert(["name": "Alice", "age": 30]) // Query documents let users = try await db["users"].find("age" >= 18).drain() // Use with Codable struct User: Codable { let name: String let age: Int } let typedUsers = try await db["users"] .find() .decode(User.self) .drain() ``` -------------------------------- ### Example: Counting Documents with CountableCursor Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Demonstrates how to use the count() method on a cursor to efficiently get the number of matching documents. ```swift let adultCount = try await users.find("age" >= 18).count() ``` -------------------------------- ### First Result Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Example showing how to retrieve the single oldest user by sorting results in descending order by age and then fetching the first result. ```swift let oldestUser = try await users.find() .sort("age", .descending) .firstResult() ``` -------------------------------- ### Swift Code Block Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/MANIFEST.md Demonstrates the use of Swift code blocks for syntax highlighting. All examples adhere to current Swift syntax. ```swift // Language specified for syntax highlighting // All examples are current Swift syntax let example = "code" ``` -------------------------------- ### Drain Cursor Examples Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Examples showing how to drain all results into an array, and how to ignore transformation errors using `failable: true`. ```swift let allUsers = try await users.find().drain() // Skip documents that fail to decode let validUsers = try await users.find() .decode(User.self) .drain(failable: true) ``` -------------------------------- ### Document Usage Examples Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Demonstrates how to create and access values within a Document, which behaves like Swift dictionaries and arrays. ```swift // Dictionary-like let doc: Document = ["name": "Alice", "age": 30] // Array-like let arr: Document = ["a", "b", "c"] // Access values if let age = doc["age"] as? Int { } ``` -------------------------------- ### MongoNamespace Usage Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Shows how to create a MongoNamespace instance for a specific collection within a database. ```swift let ns = MongoNamespace(to: "users", inDatabase: "mydb") ``` -------------------------------- ### Example: Implementing Pagination with skip() and limit() Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Demonstrates how to paginate results by combining skip() and limit() methods to fetch a specific page of data. ```swift let pageSize = 20 let page = 2 let results = try await collection.find() .sort("createdAt", .descending) .skip((page - 1) * pageSize) .limit(pageSize) .drain() ``` -------------------------------- ### Complete GridFS Workflow Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/GridFS.md Demonstrates the full lifecycle of a file in GridFS, including creating a bucket, uploading a file with metadata, finding it later, downloading it either entirely or by streaming, and finally deleting it. ```swift // Create bucket let gridFS = GridFSBucket(in: database) // Upload a file let fileData = try Data(contentsOf: url) let file = try await gridFS.upload( fileData, filename: "document.pdf", metadata: [ "contentType": "application/pdf", "uploadedBy": "user@example.com" ] ) // Find the file later if let file = try await gridFS.findFile(["filename": "document.pdf"]) { // Download and process let data = try await file.reader.readData() // Or stream for large files for try await chunk in file { // Process chunk } } // Delete when no longer needed try await gridFS.deleteFile(byId: file.id) ``` -------------------------------- ### Create an Index with Sort Order Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Example of creating an index with specified sort directions for multiple fields. ```swift Index(on: [ "createdAt": .descending, // Newest first "priority": .ascending // Low to high ]) ``` -------------------------------- ### Create ByteBuffer Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Shows how to create a ByteBuffer from a byte array. This buffer can then be used for uploading data, for example, to GridFS. ```swift let buffer = ByteBuffer(bytes: [0x01, 0x02, 0x03]) let file = try await gridFS.upload(buffer) ``` -------------------------------- ### Sorting Usage Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Demonstrates how to apply sorting to a database query using the Sorting struct. This example sorts users by age in descending order and then by name in ascending order. ```swift let results = try await users.find() .sort(["age": .descending, "name": .ascending]) ``` -------------------------------- ### MongoDB Connection String Examples Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/INDEX.md Illustrates common connection string configurations for different environments, including local development, Atlas cloud deployments, and replica sets. ```plaintext mongodb://localhost/mydb # Local dev ``` ```plaintext mongodb+srv://user:pass@cluster.mongodb.net/mydb # Atlas cloud ``` ```plaintext mongodb://server1,server2,server3/db?replicaSet=rs0 # Replica set ``` -------------------------------- ### ObjectId Usage Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Shows how to generate a new ObjectId and use it within a Document. ```swift let id = ObjectId() // Generate new ID let doc: Document = ["_id": id, "name": "Alice"] ``` -------------------------------- ### Configuring Change Stream Options Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/ChangeStreams.md Example of how to instantiate ChangeStreamOptions to specify full document retrieval on updates and set a maximum await time. ```swift let options = ChangeStreamOptions( fullDocument: .updateLookup, // Get full doc on updates maxAwaitTimeMS: 5000 // 5 second timeout ) let stream = try await collection.watch(options: options) ``` -------------------------------- ### Document Type Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Represents a BSON document, commonly used for storing data in MongoDB. Example shows a simple document with a 'name' field. ```swift ["name": "Alice"] ``` -------------------------------- ### Connect, Insert, and Query MongoDB with Swift Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/README.md Demonstrates connecting to a MongoDB database, inserting a document, and performing basic find operations using Swift's async/await syntax. Includes examples for both dynamic and type-safe queries using Codable. ```swift import MongoKitten // Connect to MongoDB let db = try await MongoDatabase.connect(to: "mongodb://localhost/mydb") // Get a collection let users = db["users"] // Insert a document try await users.insert(["name": "Alice", "age": 30]) // Query documents let results = try await users.find("age" >= 18).drain() // Type-safe queries with Codable struct User: Codable { let name: String let age: Int } let typedResults: [User] = try await users.find() .decode(User.self) .drain() ``` -------------------------------- ### Create an Index for Sorting Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Example of creating an index where fields are ordered to efficiently support sorting operations, particularly for time-series data. ```swift Index(named: "recent-posts", on: [ "status": .ascending, "createdAt": .descending ]) ``` -------------------------------- ### Start Transaction Function Signature Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Transactions.md This is the function signature for starting a new transaction. It allows configuration of auto-commit behavior and transaction-specific options. ```swift public func startTransaction( autoCommitChanges autoCommit: Bool, with options: MongoSessionOptions = .init(), transactionOptions: MongoTransactionOptions? = nil ) async throws -> MongoTransactionDatabase ``` -------------------------------- ### Basic Transaction Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Transactions.md Demonstrates a basic transaction flow. Operations are performed within a `do-catch` block, with a commit on success and an abort on any error. ```swift let transaction = try await db.startTransaction(autoCommitChanges: false) do { let users = transaction["users"] let accounts = transaction["accounts"] // Insert new user try await users.insert(["_id": userId, "name": "Alice", "email": "alice@example.com"]) // Create corresponding account try await accounts.insert(["userId": userId, "balance": 1000]) // All operations must succeed, or abort try await transaction.commit() } catch { // Abort on any error try await transaction.abort() throw error } ``` -------------------------------- ### ReadConcern Type Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Defines the consistency level for read operations. Example shows setting the read concern to '.majority'. ```swift .majority ``` -------------------------------- ### Indexes API Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/MANIFEST.md Guide to creating and managing indexes for query optimization. ```APIDOC ## Indexes ### Description Details how to create and manage indexes in MongoDB for improved query performance. ### Index Management - Create indexes using `buildIndexes`. - Supported index types: `Unique`, `TextScore`, `TTL`, `General`. - Configure sort direction. - Optimize queries using indexes. ### Best Practices - Common index configurations and performance tips. ``` -------------------------------- ### Connect to High-Availability Replica Set Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Configure a connection to a high-availability replica set. This example specifies multiple replica hosts, replicaSet name, maxPoolSize, and write concern. ```swift let uri = """ mongodb://replica1:27017,replica2:27017,replica3:27017/myapp? replicaSet=myReplicaSet& maxPoolSize=50& w=majority& journal=true """ let db = try await MongoDatabase.connect(to: uri) ``` -------------------------------- ### Configure MongoSessionOptions Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Transactions.md Set up session options for transactions, including causal consistency and retryable writes. This is used when starting a transaction. ```swift let options = MongoSessionOptions( causalConsistency: true, retryableWrites: true ) let transaction = try await db.startTransaction( autoCommitChanges: false, with: options ) ``` -------------------------------- ### Create a Compound Index Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Example of creating a compound index on multiple fields, useful for queries that filter or sort on these fields together. ```swift Index(named: "user-lookup", on: [ "userId": .ascending, "createdAt": .descending ]) ``` -------------------------------- ### Configure Connection Timeout Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Troubleshoot connection timeouts by increasing the `serverSelectionTimeoutMS` parameter in the connection URI. This example sets the timeout to 60 seconds. ```swift let uri = "mongodb://localhost/mydb?serverSelectionTimeoutMS=60000" ``` -------------------------------- ### Run MongoDB with Docker Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/INDEX.md Start a MongoDB instance in a Docker container for isolated testing. This command maps the container's port 27017 to the host's port 27017. ```bash docker run -d -p 27017:27017 mongo:6.0 ``` -------------------------------- ### Register MongoDB Database with Vapor Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Extends Vapor's `Request` and `Application` to integrate MongoKitten. Use `initializeMongoDB` before starting the application. ```swift extension Request { public var mongo: MongoDatabase { return application.mongo.adoptingLogMetadata([ "request-id": .string(id) ]) } } private struct MongoDBStorageKey: StorageKey { typealias Value = MongoDatabase } extension Application { public var mongo: MongoDatabase { get { storage[MongoDBStorageKey.self]! } set { storage[MongoDBStorageKey.self] = newValue } } public func initializeMongoDB(connectionString: String) throws { self.mongo = try MongoDatabase.lazyConnect(to: connectionString) } } ``` ```swift try app.initializeMongoDB(connectionString: "mongodb://localhost/my-app") ``` -------------------------------- ### Create a TTL Index Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Example of creating a Time-To-Live (TTL) index to automatically remove documents after a specified period. Useful for session or cache data. ```swift TTLIndex( named: "session-expire", field: "createdAt", expireAfterSeconds: 86400 // 24 hours ) ``` -------------------------------- ### Create a Unique Index Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Example of creating a unique index on a single field. Ensures that all values in the indexed field are unique. ```swift UniqueIndex(named: "email", field: "email") ``` -------------------------------- ### startTransaction Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Transactions.md Starts a new transaction on a database. This method allows for fine-grained control over database operations within a transactional boundary. ```APIDOC ## startTransaction(autoCommitChanges:with:transactionOptions:) ### Description Starts a new transaction on a database. ### Method `public func startTransaction(autoCommitChanges autoCommit: Bool, with options: MongoSessionOptions = .init(), transactionOptions: MongoTransactionOptions? = nil) async throws -> MongoTransactionDatabase` ### Parameters #### Path Parameters * `autoCommit` (Bool) - Required - Whether to auto-commit after operations * `options` (MongoSessionOptions) - Optional - Session configuration * `transactionOptions` (MongoTransactionOptions?) - Optional - Transaction-specific options ### Returns A `MongoTransactionDatabase` for executing operations. ### Throws `MongoKittenError` if transaction is not supported. ### Example ```swift let transaction = try await db.startTransaction(autoCommitChanges: false) do { let users = transaction["users"] let accounts = transaction["accounts"] // Insert new user try await users.insert(["_id": userId, "name": "Alice", "email": "alice@example.com"]) // Create corresponding account try await accounts.insert(["userId": userId, "balance": 1000]) // All operations must succeed, or abort try await transaction.commit() } catch { // Abort on any error try await transaction.abort() throw error } ``` ``` -------------------------------- ### Build Complex Aggregation Pipeline (Swift) Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/AggregationPipeline.md Construct an aggregation pipeline using builder syntax. This example demonstrates filtering with `Match`, grouping and aggregating with `Group`, sorting with `Sort`, and limiting results with `Limit`. ```swift let pipeline = collection.buildAggregate { Match(where: "status" == "active") Group([ "_id": "$category", "count": ["$sum": 1], "avgPrice": ["$avg": "$price"] ]) Sort(by: "count", direction: .descending) Limit(10) } ``` -------------------------------- ### Iterating Through Change Stream Updates Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/ChangeStreams.md Example of how to iterate through a change stream and process update operations, checking for updated and removed fields. ```swift for try await change in stream { if change.operationType == .update, let updateDesc = change.updateDescription { if let updated = updateDesc.updatedFields { for (field, value) in updated { print("Field '\(field)' changed to: \(value)") } } if let removed = updateDesc.removedFields { print("Removed fields: \(removed)") } } } ``` -------------------------------- ### Graceful Degradation for Unsupported Features Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/errors.md Implement fallback mechanisms when a server does not support a requested feature. This example shows how to catch `.unsupportedFeatureByServer` errors and use an alternative method to retrieve the data. ```swift do { let features = try await db.listCollections() } catch let error as MongoKittenError { if case .unsupportedFeatureByServer = error.errorType { // Fall back to alternative approach let manual = try await db["system.namespaces"].find().drain() } else { throw error } } ``` -------------------------------- ### Configure Session Options for Transactions Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Set session options for transactions, including causal consistency and retryable writes. These options are passed when starting a transaction. ```swift let sessionOptions = MongoSessionOptions( causalConsistency: true, retryableWrites: true ) let transaction = try await db.startTransaction( autoCommitChanges: false, with: sessionOptions ) ``` -------------------------------- ### Find Index Information with $indexStats Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Use the $indexStats aggregation stage to analyze index usage. This example filters out the default '_id' index. ```swift let stats = try await collection.buildAggregate { Match(where: "_id.name" != "_id_") }.drain() ``` -------------------------------- ### ObjectId Type Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Represents a unique identifier for MongoDB documents. Example shows instantiation of a new ObjectId. ```swift ObjectId() ``` -------------------------------- ### MongoDB URI with Write Concern Parameters Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Provides an example of a MongoDB URI that specifies write concern settings, including 'majority' write and journaling. ```swift let uri = "mongodb://localhost/mydb?w=majority&journal=true&wtimeoutMS=5000" ``` -------------------------------- ### Initialize Swift Logger Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Demonstrates how to initialize a standard Swift Logger. This logger can then be passed to connect to a MongoDB database. ```swift let logger = Logger(label: "com.example.app") let db = try await MongoDatabase.connect(to: uri, logger: logger) ``` -------------------------------- ### WriteConcern Type Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Specifies the acknowledgment requirement for write operations. Example shows setting the write concern to '.majority'. ```swift .majority() ``` -------------------------------- ### Configure Connection Pool Size Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Address connection pool exhaustion by increasing the `maxPoolSize` parameter in the connection URI. This example sets the pool size to 100. ```swift let uri = "mongodb://localhost/mydb?maxPoolSize=100" ``` -------------------------------- ### Initialize GridFSBucket Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Instantiate a `GridFSBucket` to manage file uploads and downloads within a specific database. ```swift let database: MongoDatabase = ... let gridFS = GridFSBucket(in: database) ``` -------------------------------- ### Transactions API Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/MANIFEST.md Guide to managing ACID transactions in MongoDB using MongoKitten. ```APIDOC ## Transactions ### Description Details the lifecycle and management of ACID transactions, enabling atomic operations across multiple documents or collections. ### Transaction Management - Start transactions. - Control auto-commit vs. manual commit. - Understand operation constraints within transactions. - Handle errors and perform rollbacks. - Configure session and transaction options. ### Best Practices - Guidance on using transactions effectively and safely. ``` -------------------------------- ### Building an Aggregation Pipeline Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/AggregationPipeline.md Demonstrates how to create an aggregation pipeline using the `buildAggregate` method and chain stages like Match, Group, and Sort. ```APIDOC ## buildAggregate(_:) Creates an aggregation pipeline for a collection. ### Method Signature ```swift public func buildAggregate(_ buildBlock: @escaping (AggregateBuilderPipeline) -> R) -> R ``` ### Description This method initiates the construction of an aggregation pipeline. It accepts a closure that defines the sequence of aggregation stages. ### Example ```swift let pipeline = collection.buildAggregate { Match(where: "age" >= 18) Group([ "_id": "$country", "count": ["$sum": 1] ]) Sort(by: "count", direction: .descending) } for try await result in pipeline { print(result) } ``` ``` -------------------------------- ### Monitor Queries with comment() Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Use the .explain() method with queryPlanner verbosity to analyze query plans. This can be combined with .comment() for easier identification in logs. ```swift let results = try await users.find("age" >= 18) .explain(verbosity: .queryPlanner) ``` -------------------------------- ### Define a Codable struct Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Example of a nested struct conforming to Codable for use with BSON encoders. ```swift struct User: Codable { var profile: Profile? var username: String var password: String var age: Int? struct Profile: Codable { var profilePicture: Data? var firstName: String var lastName: String } } ``` -------------------------------- ### Create ConnectionSettings from URI Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Instantiate ConnectionSettings by parsing a MongoDB connection URI string. This is a convenient way to configure connection parameters. ```swift let settings = try ConnectionSettings("mongodb://localhost/mydb") let db = try await MongoDatabase.connect(to: settings) ``` -------------------------------- ### OperationType Enum Values Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Represents the type of operation performed on a collection. Examples include '.insert' and '.update'. ```swift .insert, .update ``` -------------------------------- ### Configure SSL with Certificate Verification Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Enable SSL and configure advanced certificate settings via ConnectionSettings. Further SSL configuration is handled at the NIO level. ```swift // Set via ConnectionSettings for advanced control var settings = try ConnectionSettings("mongodb://localhost/mydb?ssl=true") settings.ssl = true // Additional certificate configuration would be done at the NIO level ``` -------------------------------- ### Get Cursor Connection Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Retrieves the underlying MongoConnection associated with the cursor. This connection is used for all cursor operations. ```swift func getConnection() async throws -> MongoConnection ``` -------------------------------- ### connect(to:logger:) Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Immediately establishes a connection to a MongoDB database using connection settings. Throws MongoKittenError if the connection fails or no target database is specified. ```APIDOC ## connect(to:logger:) ### Description Immediately establishes a connection to a MongoDB database using connection settings. ### Method `public static func connect( to settings: ConnectionSettings, logger: Logger = Logger(label: "org.orlandos-nl.mongokitten") ) async throws -> MongoDatabase ### Parameters #### Path Parameters - **settings** (ConnectionSettings) - Required - Connection settings including authentication and target database - **logger** (Logger) - Optional - Default logger - Logger for database operations ### Returns A connected database instance ready for use. ### Throws `MongoKittenError` if the connection fails or no target database is specified. ``` -------------------------------- ### Connect to MongoDB Database Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Establishes an immediate connection to a MongoDB database. Ensure the connection string is valid. ```swift import MongoKitten let db = try await MongoDatabase.connect(to: "mongodb://localhost/my_database") ``` -------------------------------- ### Handle Cursor Errors Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/errors.md Catch and handle .cursorError when operating on a cursor, for example, attempting to close an already closed cursor. ```swift do { try await cursor.close() try await cursor.close() // Error: already closed } catch let error as MongoKittenError { if case .cursorError = error.errorType { print("Cursor operation failed") } } ``` -------------------------------- ### Manually Create ConnectionSettings Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Manually create and configure ConnectionSettings properties for fine-grained control over connection parameters. Useful when not using a URI string. ```swift var settings = ConnectionSettings() settings.hosts = [("localhost", 27017)] settings.username = "user" settings.password = "pass" settings.authSource = "admin" settings.targetDatabase = "mydb" settings.ssl = true let db = try await MongoDatabase.connect(to: settings) ``` -------------------------------- ### Explain Query Execution Plan Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Retrieves detailed information about how the query is executed on the server. The verbosity level can be adjusted. ```swift public func explain( verbosity: ExplainVerbosity = .allPlansExecution ) async throws -> Document ``` -------------------------------- ### connect(to:logger:) Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Immediately establishes a connection to a MongoDB database using a connection string. Throws MongoKittenError if the connection fails. ```APIDOC ## connect(to:logger:) ### Description Immediately establishes a connection to a MongoDB database using a connection string. ### Method `public static func connect( to uri: String, logger: Logger = Logger(label: "org.orlandos-nl.mongokitten") ) async throws -> MongoDatabase ### Parameters #### Path Parameters - **uri** (String) - Required - A MongoDB connection string (e.g., "mongodb://localhost/myapp") - **logger** (Logger) - Optional - Default logger - Logger for database operations ### Returns A connected database instance ready for use. ### Throws `MongoKittenError` if the connection fails. ### Example ```swift let db = try await MongoDatabase.connect( to: "mongodb://user:pass@localhost/myapp" ) ``` ``` -------------------------------- ### Check Index Usage with .explain() Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Use the .explain() method to inspect query execution plans and verify index usage. Look for 'IXSCAN' (good) instead of 'COLLSCAN' (bad). ```swift let explanation = try await users.find("age" >= 18) .explain(verbosity: .allPlansExecution) ``` -------------------------------- ### Define a Basic Model Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Create a model by conforming to the Model protocol. ```swift import Meow struct User: Model { .. } ``` -------------------------------- ### Count Documents Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MeowORM.md Counts the number of documents that match the given filter. This is an efficient way to get a count without fetching the documents themselves. ```swift public func count( where filter: @escaping (M) -> Q ) async throws -> Int ``` ```swift let adultCount = try await users.count(where: { user in user.$age >= 18 }) ``` -------------------------------- ### Import Meow Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Include the Meow module in your source files. ```swift import Meow ``` -------------------------------- ### Count Aggregation Results Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/AggregationPipeline.md Use `count()` to get the total number of documents that match the aggregation pipeline. This operation is performed asynchronously. ```swift let count = try await pipeline.count() ``` -------------------------------- ### Instantiate a User struct Source: https://github.com/orlandos-nl/mongokitten/wiki/Using-BSON Create an instance of the User struct. ```swift let user = User(uniqueIdentifier: ObjectId(), username: "Joannis", password: [0x00, 0x01, 0x02, 0x03, 0x04], age: 20, male: true, registrationDate: Date()) ``` -------------------------------- ### Document vs. Codable Data Handling Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/INDEX.md Illustrates how to work with both untyped BSON Documents and strongly-typed Codable structs for data retrieval. ```swift // Untyped (Document) let doc = try await collection.findOne() if let name = doc?["name"] as? String { } ``` ```swift // Typed (Codable) struct User: Decodable { let name: String } let user = try await collection.findOne(as: User.self) ``` -------------------------------- ### Connect to MongoDB using ConnectionSettings Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Establishes an immediate connection to a MongoDB database using a ConnectionSettings object. This method is useful when connection details are managed programmatically. ```swift public static func connect( to settings: ConnectionSettings, logger: Logger = Logger(label: "org.orlandos-nl.mongokitten") ) async throws -> MongoDatabase ``` -------------------------------- ### GridFSBucket Initialization Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/GridFS.md Creates a new GridFS bucket. You can specify a custom name prefix for the bucket or use the default 'fs'. ```APIDOC ## GridFSBucket Initialization ### Description Creates a new GridFS bucket. You can specify a custom name prefix for the bucket or use the default 'fs'. ### Method `init(named:in:)` ### Parameters #### Path Parameters - `name` (String) - Optional - Default: "fs" - The bucket name prefix - `database` (MongoDatabase) - Required - The database to store files in ### Request Example ```swift let gridFS = GridFSBucket(in: database) let customBucket = GridFSBucket(named: "uploads", in: database) ``` ``` -------------------------------- ### Connect to MongoDB using URI Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Establishes an immediate connection to a MongoDB database using a connection string. Ensure the URI is valid and includes necessary credentials and database name. ```swift let db = try await MongoDatabase.connect( to: "mongodb://user:pass@localhost/myapp" ) ``` -------------------------------- ### Start Transaction Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Initiates a new MongoDB transaction, allowing for atomic execution of multiple operations. Transactions can be configured for automatic or manual commit. ```APIDOC ## startTransaction(autoCommitChanges:with:transactionOptions:) ### Description Starts a new MongoDB transaction for atomic multi-document operations. ### Method public func startTransaction( autoCommitChanges autoCommit: Bool, with options: MongoSessionOptions = .init(), transactionOptions: MongoTransactionOptions? = nil ) async throws -> MongoTransactionDatabase ### Parameters #### Path Parameters - **autoCommit** (Bool) - Required - If true, the transaction automatically commits after successful operations - **options** (MongoSessionOptions) - Optional - Session options for the transaction (Default: `.init()`) - **transactionOptions** (MongoTransactionOptions?) - Optional - Optional transaction-specific options (Default: `nil`) ### Returns A `MongoTransactionDatabase` instance for executing operations within the transaction. ### Throws `MongoKittenError` if transactions are not supported by the server. ### Request Example ```swift let transaction = try await db.startTransaction(autoCommitChanges: false) let users = transaction["users"] try await users.insertOne(["name": "Alice"]) try await transaction.commit() ``` ``` -------------------------------- ### Create GridFSBucket Instance Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/GridFS.md Instantiate a GridFSBucket to manage GridFS files. You can use the default bucket name 'fs' or specify a custom name. ```swift let gridFS = GridFSBucket(in: database) let customBucket = GridFSBucket(named: "uploads", in: database) ``` -------------------------------- ### Build Search/Content Collection Indexes Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Indexes.md Sets up indexes for search and content collections, including a text score index for full-text search on content and a compound index for filtering by category and date. ```swift try await articles.buildIndexes { // Full-text search TextScoreIndex(named: "content-search", field: "content") // Category and date filtering Index(named: "category-date", on: [ "category": .ascending, "publishedAt": .descending ]) } ``` -------------------------------- ### Perform Aggregation in MongoDB Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/INDEX.md Execute complex data aggregation pipelines using a fluent API. This example demonstrates matching, grouping, sorting, and limiting results. ```swift try await collection.buildAggregate { Match(where: "status" == "active") Group(["_id": "$category", "count": ["$sum": 1]]) Sort(by: "count", direction: .descending) Limit(10) } ``` -------------------------------- ### Vapor Integration: Access Database in Routes Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/INDEX.md Demonstrates how to access the registered MongoDB database within Vapor routes to perform operations like finding documents. ```swift // Access in routes app.get("users") { req async throws in let users = try await req.application.mongo["users"].find().drain() return users } ``` -------------------------------- ### Lazy Cursor Evaluation Example Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/INDEX.md Demonstrates lazy evaluation of cursors. Database operations are deferred until the cursor's results are explicitly consumed using '.drain()'. ```swift let cursor = users.find("age" > 18) // Not executed yet let sorted = cursor.sort("name", .ascending) // Still not executed let results = try await sorted.drain() // Now it executes ``` -------------------------------- ### Basic MongoDB Connection Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Establishes a connection to a MongoDB database using a basic URI string. ```swift let db = try await MongoDatabase.connect(to: "mongodb://localhost/myapp") ``` -------------------------------- ### Configuration Reference Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/MANIFEST.md Details on configuring MongoDB connections, pooling, and other library settings. ```APIDOC ## Configuration Reference ### Description Guides users through configuring MongoKitten, including connection strings, pooling, security, and operational parameters. ### Connection Configuration - MongoDB URI connection strings and parameters (authentication, behavior, read preferences, write behavior). - `ConnectionSettings` structure. - Connection strategy (`connect` vs. `lazyConnect`). - SSL/TLS configuration. ### Operational Configuration - Logger configuration. - Connection pooling tuning. - Transaction configuration. - Write/read concern levels. ### Advanced Topics - Environment-based configuration. - Common configuration patterns. - Troubleshooting guide. ``` -------------------------------- ### Lazy Connection with MongoDatabase.lazyConnect Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Ideal for development and testing, this method allows the app to start without blocking and auto-reconnects in the background. Errors are discovered upon the first operation. ```swift // Best for: Development, testing, flexible deployment let db = try MongoDatabase.lazyConnect(to: "mongodb://localhost/mydb") ``` -------------------------------- ### Immediate Connection with MongoDatabase.connect Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Use for production environments to ensure the connection is verified at startup. This method blocks app startup but provides immediate feedback on connection issues. ```swift // Best for: Production, immediate feedback on connection issues let db = try await MongoDatabase.connect(to: "mongodb://localhost/mydb") ``` -------------------------------- ### Access a Collection using Subscript Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Use the subscript operator to get a reference to a specific collection within the database. This is the primary way to interact with collections for performing operations. ```swift public subscript(collection: String) -> MongoCollection ``` ```swift let users = db["users"] let products = db["products"] ``` -------------------------------- ### MeowDatabase Creation Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MeowORM.md Instantiate MeowDatabase by passing a connected MongoDatabase instance. ```APIDOC ## MeowDatabase Creation ### Description Instantiate MeowDatabase by passing a connected MongoDatabase instance. ### Code Example ```swift // From a MongoDatabase let mongoDB = try await MongoDatabase.connect(to: "mongodb://localhost/mydb") let meow = MeowDatabase(mongoDB) ``` ``` -------------------------------- ### Start Transaction with Auto-Commit Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/Transactions.md Initiates a database transaction that automatically commits all changes once all operations within it are successfully completed. This is useful for simpler transaction flows where explicit commit/abort is not required. ```swift let transaction = try await db.startTransaction(autoCommitChanges: true) let users = transaction["users"] try await users.insert(["name": "Bob", "email": "bob@example.com"]) // Automatically committed ``` -------------------------------- ### MeowDatabase Creation in Swift Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MeowORM.md Initializes a MeowDatabase instance from an existing MongoDatabase connection. This is the primary interface for interacting with Meow models. ```swift // From a MongoDatabase let mongoDB = try await MongoDatabase.connect(to: "mongodb://localhost/mydb") let meow = MeowDatabase(mongoDB) ``` -------------------------------- ### Get First Aggregation Result Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/AggregationPipeline.md Use `firstResult()` to efficiently retrieve only the first document from the aggregation pipeline. This operation is optimized to fetch a single document from the server and returns `nil` if no documents are found. ```swift public func firstResult() async throws -> Element? ``` -------------------------------- ### Connect to MongoDB Database Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/INDEX.md Establish a connection to a MongoDB database. Supports immediate or lazy connection. ```swift import MongoKitten // Immediate connection let db = try await MongoDatabase.connect(to: "mongodb://localhost/mydb") // Or lazy connection (defers until first operation) let db = try MongoDatabase.lazyConnect(to: "mongodb://localhost/mydb") ``` -------------------------------- ### Iterate over a Document Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Demonstrates iterating over keys and values in a Document using standard Swift loops. ```swift for (key, value) in documentA { // ... } for value in documentB.values { // ... } ``` -------------------------------- ### ChangeStreamOptions Swift Struct Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Defines options for configuring change streams, such as including full documents, resuming from a specific point, setting a start time, defining collation, and specifying maximum wait time. ```swift public struct ChangeStreamOptions: Codable ``` -------------------------------- ### lazyConnect(to:logger:) Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Defers connection establishment using connection settings. Throws MongoKittenError if connection settings are invalid or no target database is specified. ```APIDOC ## lazyConnect(to:logger:) ### Description Defers connection establishment using connection settings. ### Method `public static func lazyConnect( to settings: ConnectionSettings, logger: Logger = Logger(label: "org.orlandos-nl.mongokitten") ) throws -> MongoDatabase ### Parameters #### Path Parameters - **settings** (ConnectionSettings) - Required - Connection settings including authentication and target database - **logger** (Logger) - Optional - Default logger - Logger for database operations ### Returns A database instance that will connect lazily. ### Throws `MongoKittenError` if connection settings are invalid or no target database is specified. ``` -------------------------------- ### Watch a Model's Collection with Meow ORM Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/ChangeStreams.md Integrate change streams directly with your Meow ORM models to easily monitor changes to a specific collection. This example shows how to watch for changes to the `User` model. ```swift struct User: Model { ... } let stream = try await User.watch(in: meow) for try await change in stream { if let user = change.fullDocument { print("User changed: \(user.name)") } } ``` -------------------------------- ### Access Collection and Query Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Retrieve a collection instance and perform type-checked queries using the $ prefix. ```swift let users = meow[User.self] ``` ```swift let adultCount = try await users.count(matching: { user in user.$profile.$age >= 18 }) ``` ```swift let kids = try await users.find(matching: { user in user.$profile.$age < 18 }) for try await kid in kids { // TODO: Send verification email to parents } ``` -------------------------------- ### Create a Type-Safe Change Stream Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/ChangeStreams.md This method creates a change stream that decodes documents into a specified Codable type. It's useful for working with strongly-typed data models and requires the same backend setup as generic change streams. ```swift struct User: Codable { let _id: ObjectId let name: String let email: String let age: Int } let typedStream = try await users.watch(type: User.self) for try await change in typedStream { if let user = change.fullDocument { print("User modified: \(user.name)") } } ``` -------------------------------- ### Lazy Connect to MongoDB using URI Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Defers connection establishment until the first database operation is performed. This is useful for applications that may not immediately need to connect. ```swift let db = try MongoDatabase.lazyConnect( to: "mongodb://localhost/myapp" ) ``` -------------------------------- ### Start a Transaction Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Initiates a new MongoDB transaction to ensure atomic operations across multiple documents. You can control whether changes are automatically committed upon successful completion. This returns a `MongoTransactionDatabase` instance for operations within the transaction. ```swift public func startTransaction( autoCommitChanges autoCommit: Bool, with options: MongoSessionOptions = .init(), transactionOptions: MongoTransactionOptions? = nil ) async throws -> MongoTransactionDatabase ``` ```swift let transaction = try await db.startTransaction(autoCommitChanges: false) let users = transaction["users"] try await users.insertOne(["name": "Alice"]) try await transaction.commit() ``` -------------------------------- ### Configure Connection Pooling with URI Parameters Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Configure connection pooling by appending parameters like maxPoolSize, minPoolSize, maxIdleTimeMS, and waitQueueTimeoutMS to the MongoDB connection URI. ```swift let uri = """ mongodb://localhost/mydb? maxPoolSize=50& minPoolSize=10& maxIdleTimeMS=30000& waitQueueTimeoutMS=5000 """ let db = try await MongoDatabase.connect(to: uri) ``` -------------------------------- ### Lazy Connect to MongoDB using ConnectionSettings Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Defers connection establishment using a ConnectionSettings object. The connection will be made upon the first database operation. ```swift public static func lazyConnect( to settings: ConnectionSettings, logger: Logger = Logger(label: "org.orlandos-nl.mongokitten") ) throws -> MongoDatabase ``` -------------------------------- ### execute() Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/QueryCursors.md Executes the cursor and returns a finalized cursor ready for batch processing. ```APIDOC ## execute() ### Description Executes the cursor and returns a finalized cursor for batch processing. ### Method `execute()` ### Returns A `FinalizedCursor` ready to iterate over results. ### Source `Sources/MongoKitten/Cursor.swift:132` ``` -------------------------------- ### lazyConnect(to:logger:) Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Defers connection establishment until the first database operation is performed. Throws MongoKittenError if connection settings are invalid. ```APIDOC ## lazyConnect(to:logger:) ### Description Defers connection establishment until the first database operation is performed. ### Method `public static func lazyConnect( to uri: String, logger: Logger = Logger(label: "org.orlandos-nl.mongokitten") ) throws -> MongoDatabase ### Parameters #### Path Parameters - **uri** (String) - Required - A MongoDB connection string (e.g., "mongodb://localhost/myapp") - **logger** (Logger) - Optional - Default logger - Logger for database operations ### Returns A database instance that will connect lazily. ### Throws `MongoKittenError` if connection settings are invalid (not yet connected to server). ### Example ```swift let db = try MongoDatabase.lazyConnect( to: "mongodb://localhost/myapp" ) ``` ``` -------------------------------- ### Find First Document by Query Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoCollection.md Retrieves the first document that matches the provided query. Returns nil if no documents match. ```swift if let user = try await users.findOne("username" == "alice") { print(user) } ``` -------------------------------- ### Configure Logging Metadata Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Attaches metadata to a database instance for logging and monitoring purposes. ```swift // Add logging metadata let loggedDb = db.adoptingLogMetadata([ "service": "user-api", "environment": "production" ]) // Use the logged database let users = loggedDb["users"] ``` -------------------------------- ### Build Simple Equality Queries Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MeowORM.md Use the `$` prefix with model properties for simple equality checks in queries. This is useful for finding records that match a specific value. ```swift users.find(matching: { user in user.$username == "alice" }) ``` -------------------------------- ### List Databases in MongoKitten Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Use this method to retrieve a list of all databases accessible by the current user in the MongoDB cluster. It returns an array of MongoDatabase instances. ```swift public func listDatabases() async throws -> [MongoDatabase] ``` -------------------------------- ### Adopting Log Metadata Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Creates a new instance of the database with additional logging metadata attached. This is useful for tracing operations within a specific context. ```APIDOC ## adoptingLogMetadata(_:) ### Description Creates a new database instance with the specified logging metadata. ### Method public func adoptingLogMetadata(_ metadata: Logger.Metadata) -> MongoDatabase ### Parameters #### Path Parameters - **metadata** (Logger.Metadata) - Required - The logging metadata to attach to database operations ### Returns A new database instance with the specified metadata. ### Request Example ```swift let dbWithMetadata = db.adoptingLogMetadata([ "request_id": "123", "user_id": "456" ]) ``` ``` -------------------------------- ### MongoSessionOptions Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/types.md Configuration options for creating a client session. ```APIDOC ## MongoSessionOptions Options for creating a session. ### Struct Definition ```swift public struct MongoSessionOptions ``` ### Properties - `causalConsistency` (Bool?) - Enable causal consistency - `retryableWrites` (Bool?) - Enable retryable writes - `defaultTransactionOptions` (MongoTransactionOptions?) - Default transaction options ``` -------------------------------- ### MongoDB URI with Connection Behavior Parameters Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Shows a MongoDB URI with parameters controlling connection pool size, idle time, and write retries. ```swift let uri = "mongodb://localhost/mydb?maxPoolSize=50&maxIdleTimeMS=60000&retryWrites=true" ``` -------------------------------- ### Enable SSL for Connection Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Connect to a MongoDB instance using SSL/TLS by appending '?ssl=true' to the connection URI. ```swift let uri = "mongodb://localhost/mydb?ssl=true" let db = try await MongoDatabase.connect(to: uri) ``` -------------------------------- ### Integrate Meow with Vapor Source: https://github.com/orlandos-nl/mongokitten/blob/main/README.md Extend Application and Request to provide access to the Meow database. ```swift extension Application { public var meow: MeowDatabase { MeowDatabase(mongo) } } extension Request { public var meow: MeowDatabase { MeowDatabase(mongo) } } ``` -------------------------------- ### InsertReply Error Handling Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/errors.md Shows how to check the 'ok' property of an InsertReply and throw it as an error if the operation failed. It also demonstrates iterating through write errors. ```swift do { let reply = try await collection.insertMany(documents) if reply.ok != 1 { throw reply // Throws the InsertReply as an error } } catch let reply as InsertReply { for error in reply.writeErrors ?? [] { print("Error at index \(error.index): \(error.message)") } } ``` -------------------------------- ### Connect with a Custom Logger Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Integrate a custom `Logging` instance with Mongokitten for centralized logging. Ensure the logger's log level is set appropriately. ```swift import Logging let logger = Logger(label: "com.example.mongodb") logger.logLevel = .debug let db = try await MongoDatabase.connect( to: "mongodb://localhost/mydb", logger: logger ) ``` -------------------------------- ### listDatabases() Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoDatabase.md Lists all databases your user has knowledge of in the cluster. ```APIDOC ## listDatabases() ### Description Lists all databases your user has knowledge of in the cluster. ### Method `listDatabases()` ### Returns An array of `MongoDatabase` instances for each database. ``` -------------------------------- ### MongoDB URI with Authentication Parameters Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/configuration.md Demonstrates a MongoDB URI string that includes authentication-related parameters like authSource and authMechanism. ```swift let uri = "mongodb://user:pass@localhost/mydb?authSource=admin&authMechanism=SCRAM-SHA-256" ``` -------------------------------- ### Build Comparison Queries Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MeowORM.md Combine comparison operators like `>`, `<=`, and `&&` to build queries with numerical or date range constraints. Ensure properties are comparable. ```swift users.find(matching: { user in user.$age > 18 && user.$age <= 65 }) ``` -------------------------------- ### Initialize GridFS File Writer Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/GridFS.md Create a new GridFSFileWriter instance to begin a streaming file upload to a specified GridFS bucket. This operation can throw a GridFSError if initialization fails. ```swift let writer = try await GridFSFileWriter(toBucket: gridFS) ``` -------------------------------- ### Enable Disk Usage for Aggregation Pipeline Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/AggregationPipeline.md Allows disk usage for aggregation pipelines that might exceed memory limits. Call this method to enable. ```swift let pipeline = collection.buildAggregate { Sort(by: "timestamp", direction: .ascending) } .allowDiskUse() ``` -------------------------------- ### buildAggregate(_:) Source: https://github.com/orlandos-nl/mongokitten/blob/main/_autodocs/api-reference/MongoCollection.md Creates an aggregation pipeline for complex data processing on the collection. ```APIDOC ## buildAggregate(_:) ### Description Creates an aggregation pipeline. ### Returns An `AggregateBuilderPipeline` for building the aggregation. ```