### Start mongod for Test Suite Source: https://github.com/mongodb/mongo-java-driver/blob/main/README.md Start a mongod instance with the necessary parameter for the driver's test suite. Ensure mongod is running on port 27017. ```bash mkdir -p data/db mongod --dbpath ./data/db --logpath ./data/mongod.log --port 27017 --logappend --fork --setParameter enableTestCommands=1 ``` -------------------------------- ### Starting a Session Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Initiates a new ClientSession, which is a prerequisite for starting transactions. ```APIDOC ## Starting a Session Initiates a new ClientSession, which is a prerequisite for starting transactions. ### Method Signature ```java ClientSession session = client.startSession(); ``` ``` -------------------------------- ### Example MongoClientSettings Configuration Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md This snippet shows a comprehensive example of configuring MongoClientSettings, including connection string, write concern, read preference, retryable writes, and detailed settings for cluster, connection pool, socket, and SSL/TLS. ```java MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("mongodb://localhost:27017")) .writeConcern(WriteConcern.MAJORITY) .readPreference(ReadPreference.primary()) .retryWrites(true) .retryReads(true) .applyToClusterSettings(builder -> builder.serverSelectionTimeoutMS(30000)) .applyToConnectionPoolSettings(builder -> builder.maxSize(100) .minSize(10) .maxWaitTimeMS(30000)) .applyToSocketSettings(builder -> builder.connectTimeoutMS(10000) .readTimeoutMS(0)) .applyToSslSettings(builder -> builder.enabled(true) .invalidHostNameAllowed(false)) .build(); MongoClient client = MongoClients.create(settings); ``` -------------------------------- ### Start Transaction with Options Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Starts a transaction with custom configuration options, including WriteConcern, ReadPreference, and ReadConcern. Import: com.mongodb.TransactionOptions. ```java TransactionOptions options = TransactionOptions.builder() .writeConcern(WriteConcern.MAJORITY) .readPreference(ReadPreference.primary()) .readConcern(ReadConcern.MAJORITY) .build(); session.startTransaction(options); ``` -------------------------------- ### Proxy Configuration Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Configures the driver to use a SOCKS5 proxy for connections. Provide the proxy hostname, port, and authentication credentials if required. ```text mongodb://host/?proxyHost=proxy.company.com&proxyPort=1080&proxyUsername=user&proxyPassword=pass ``` -------------------------------- ### Start a ClientSession Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Initiates a client session required for managing transactions. Import: com.mongodb.client.ClientSession. ```java ClientSession session = client.startSession(); ``` -------------------------------- ### Basic MongoDB Connection Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Connect to a MongoDB instance running on localhost:27017 with default settings. This is the simplest way to get started. ```java // Simplest case - connect to localhost:27017 MongoClient client = MongoClients.create(); MongoDatabase db = client.getDatabase("myapp"); MongoCollection collection = db.getCollection("users"); ``` -------------------------------- ### MongoDB Transactions Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/README.md Basic transaction example demonstrating starting, committing, and aborting transactions, and including the session in operations. ```java // Basic transaction ClientSession session = client.startSession(); try { session.startTransaction(); // All operations must include session collection.updateOne(session, filter, update); otherCollection.insertOne(session, doc); session.commitTransaction(); } catch (Exception e) { session.abortTransaction(); throw e; } finally { session.close(); } ``` -------------------------------- ### Create and Manage Indexes in MongoDB Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/README.md Examples for creating single, unique, and compound indexes, creating multiple indexes, listing, and dropping indexes. ```java // Create single index collection.createIndex(new Document("email", 1)); ``` ```java // Create unique index collection.createIndex( new Document("email", 1), new CreateIndexOptions().unique(true) ); ``` ```java // Create compound index collection.createIndex( new Document("category", 1).append("date", -1) ); ``` ```java // Create multiple indexes collection.createIndexes(Arrays.asList( new IndexModel(new Document("email", 1), new CreateIndexOptions().unique(true)), new IndexModel(new Document("username", 1)) )); ``` ```java // List indexes collection.listIndexes().forEach(doc -> System.out.println(doc)); ``` ```java // Drop index collection.dropIndex("email_1"); ``` -------------------------------- ### MongoDB Aggregation Pipeline Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/README.md A simple aggregation pipeline example demonstrating match, group, sort, and limit stages. ```java // Simple pipeline List pipeline = Arrays.asList( Aggregates.match(Filters.eq("status", "active")), Aggregates.group("$category", Accumulators.sum("total", "$price")), Aggregates.sort(Sorts.descending("total")), Aggregates.limit(10) ); collection.aggregate(pipeline) .forEach(doc -> System.out.println(doc)); ``` -------------------------------- ### Server Selection Timeout Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Configures how long the driver waits for server selection and the latency window for multi-server selection. Use this to control responsiveness during initial connection or topology changes. ```text mongodb://localhost/?serverSelectionTimeoutMS=10000&localThresholdMS=20 ``` -------------------------------- ### Joining with Lookup Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Example demonstrating how to join documents from the current collection with documents from an 'orders' collection using the $lookup stage. ```APIDOC ## Joining with Lookup ### Description Performs a left outer join with the 'orders' collection, matching on customer ID and adding the matched orders as an array field named 'orders'. ### Example ```java List pipeline = Arrays.asList( new Document("$lookup", new Document("from", "orders") .append("localField", "_id") .append("foreignField", "customerId") .append("as", "orders")) ); collection.aggregate(pipeline) .forEach(doc -> System.out.println(doc)); ``` ``` -------------------------------- ### Connection Pool Configuration Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Sets the minimum and maximum number of connections in the pool, as well as the maximum number of concurrent connections being established. Tune these parameters to optimize performance and resource usage. ```text mongodb://localhost/?maxPoolSize=50&minPoolSize=10&maxConnecting=5 ``` -------------------------------- ### Example Aggregation Pipeline with Aggregates Builder Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Demonstrates building an aggregation pipeline using the `Aggregates` builder class. This pipeline filters documents, groups them by category, calculates the total price for each category, sorts the results by total price in descending order, and limits the output to the top 10. ```java import static com.mongodb.client.model.Aggregates.*; import static com.mongodb.client.model.Filters.*; import static com.mongodb.client.model.Accumulators.*; List pipeline = Arrays.asList( match(eq("status", "active")), group("$category", sum("total", "$price")), sort(Sorts.descending("total")), limit(10) ); collection.aggregate(pipeline) .forEach(doc -> System.out.println(doc)); ``` -------------------------------- ### Build a Filter Query Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Use the filter method with Filters.* to specify query criteria. This example filters by status and age. ```java FindIterable query = collection.find() .filter(Filters.and( Filters.eq("status", "active"), Filters.gte("age", 18) )); ``` -------------------------------- ### TLS Connection and Timeouts Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Enables TLS/SSL encryption for secure connections and sets timeouts for establishing connections and socket operations. Use `tls=true` for encryption and adjust `connectTimeoutMS` for connection establishment. ```text mongodb+srv://user:pass@cluster.mongodb.net/?tls=true&connectTimeoutMS=5000 ``` -------------------------------- ### Read Preference with Tags Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Sets the read preference to 'secondary' and specifies tag sets to filter which secondaries can be read from. This allows for directing read traffic to specific data centers or racks. ```text mongodb://host1,host2/?readPreference=secondary&readPreferenceTags=rack:A,dc:us-east ``` -------------------------------- ### Replica Set Configuration Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Specifies the replica set name to ensure the driver connects to all members of a replica set. This is crucial for high availability and fault tolerance. ```text mongodb://host1,host2,host3/?replicaSet=myReplicaSet ``` -------------------------------- ### GridFS for Large Files in MongoDB Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/README.md Examples for uploading, downloading, listing, and deleting large files using GridFS. ```java GridFSBucket bucket = GridFSBuckets.create(db); // Upload from file try (FileInputStream fis = new FileInputStream("large-file.bin")) { ObjectId fileId = bucket.uploadFromStream("large-file.bin", fis); } // Download to file try (FileOutputStream fos = new FileOutputStream("downloaded.bin")) { bucket.downloadToStream(fileId, fos); } // List files bucket.find() .forEach(file -> System.out.println(file.getFilename())); // Delete file bucket.delete(fileId); ``` -------------------------------- ### Basic Transaction Pattern Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Illustrates the fundamental structure for executing operations within a transaction, including starting, committing, and aborting. ```APIDOC ## Basic Transaction Pattern Illustrates the fundamental structure for executing operations within a transaction, including starting, committing, and aborting. ### Code Example ```java ClientSession session = client.startSession(); try { session.startTransaction(); // Multiple operations in transaction collection1.updateOne(session, filter1, update1); collection2.deleteOne(session, filter2); collection3.insertOne(session, doc3); session.commitTransaction(); } catch (Exception e) { session.abortTransaction(); throw e; } finally { session.close(); } ``` ``` -------------------------------- ### Basic Transaction Pattern Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Demonstrates the standard pattern for executing operations within a transaction, including starting, committing, and aborting. Ensures operations are atomic. ```java ClientSession session = client.startSession(); try { session.startTransaction(); // Multiple operations in transaction collection1.updateOne(session, filter1, update1); collection2.deleteOne(session, filter2); collection3.insertOne(session, doc3); session.commitTransaction(); } catch (Exception e) { session.abortTransaction(); throw e; } finally { session.close(); } ``` -------------------------------- ### Run Formatting, Docs, and Tests with Gradle Source: https://github.com/mongodb/mongo-java-driver/blob/main/AGENTS.md Execute the spotlessApply task for formatting and documentation, followed by docs, check, and scalaCheck for static analysis and tests. This command ensures code quality and adherence to project standards before submission. ```bash ./gradlew spotlessApply docs check scalaCheck ``` -------------------------------- ### Start a Transaction Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Begins a new transaction on an active client session. Throws IllegalStateException if a transaction is already active. Automatically aborted if connection drops. ```java void startTransaction() ``` -------------------------------- ### Group and Count Documents Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Example of an aggregation pipeline that groups documents by category, counting and averaging prices within each group. The results are then processed using forEach. ```java List pipeline = Arrays.asList( new Document("$match", new Document("status", "active")), new Document("$group", new Document("_id", "$category") .append("count", new Document("$sum", 1)) .append("avgPrice", new Document("$avg", "$price"))) ); collection.aggregate(pipeline) .forEach(doc -> System.out.println(doc)); ``` -------------------------------- ### Complete Transaction Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Demonstrates a complete fund transfer operation using MongoDB transactions. This includes debiting from one account, crediting another, and logging the transaction, all within a single atomic operation. ```java public void transferFunds(String from, String to, double amount) { ClientSession session = client.startSession(); try { session.startTransaction(); // Debit from source collection.updateOne( session, Filters.eq("_id", from), Updates.inc("balance", -amount) ); // Credit to destination collection.updateOne( session, Filters.eq("_id", to), Updates.inc("balance", amount) ); // Record transaction logsCollection.insertOne( session, new Document("from", from) .append("to", to) .append("amount", amount) .append("timestamp", new Date()) ); session.commitTransaction(); System.out.println("Transfer complete"); } catch (Exception e) { session.abortTransaction(); System.err.println("Transfer failed: " + e.getMessage()); throw e; } finally { session.close(); } } ``` -------------------------------- ### Get Inserted ID from InsertOneResult Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/types.md Retrieves the _id of a single document inserted into a MongoDB collection. Ensure the write was acknowledged to get a valid ID. ```java InsertOneResult result = collection.insertOne(doc); BsonValue id = result.getInsertedId(); ObjectId insertedId = id.asObjectId().getValue(); ``` -------------------------------- ### Build and Test bson-kotlinx Source: https://github.com/mongodb/mongo-java-driver/blob/main/bson-kotlinx/AGENTS.md Commands to build and run tests for the bson-kotlinx module. ```bash ./gradlew :bson-kotlinx:test ./gradlew :bson-kotlinx:check ``` -------------------------------- ### Specify Fields to Return (Projection) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Control which fields are returned in the results using the projection method with Projections.*. This example includes 'name' and 'email' while excluding 'password'. ```java query.projection(Projections.fields( Projections.include("name", "email"), Projections.exclude("password") )); ``` -------------------------------- ### getName() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets the name of the database. ```APIDOC ## getName() ### Description Gets the name of the database. ### Method GET (Conceptual) ### Endpoint N/A (Method Call) ### Parameters None ### Return Type String ### Return Values The name of the database. ### Example ```java MongoDatabase db = client.getDatabase("myapp"); System.out.println(db.getName()); // Output: myapp ``` ``` -------------------------------- ### Configure Compression Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Enable compression for the connection and specify algorithms and levels. Supports 'snappy' and 'zlib'. ```url mongodb://localhost/?compressors=snappy,zlib&zlibCompressionLevel=7 ``` -------------------------------- ### Join Documents with Lookup Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Example of an aggregation pipeline using the $lookup stage to perform a left outer join with another collection ('orders'). Results are processed using forEach. ```java List pipeline = Arrays.asList( new Document("$lookup", new Document("from", "orders") .append("localField", "_id") .append("foreignField", "customerId") .append("as", "orders")) ); collection.aggregate(pipeline) .forEach(doc -> System.out.println(doc)); ``` -------------------------------- ### getReadConcern() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets the read concern for the database. ```APIDOC ## getReadConcern() ### Description Gets the read concern for the database. ### Method GET (Conceptual) ### Endpoint N/A (Method Call) ### Parameters None ### Return Type com.mongodb.ReadConcern ### Return Values The read concern configured for this database. ### Example ```java ReadConcern concern = db.getReadConcern(); ``` ``` -------------------------------- ### Project Directory Structure Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/MANIFEST.md This code block displays the expected directory structure for the MongoDB Java Driver documentation output. It serves as a guide to locating specific documentation files. ```bash ``` /workspace/home/output/ ├── README.md # Start here - overview & quick start ├── INDEX.md # Complete inventory & cross-reference ├── MANIFEST.md # This file ├── configuration.md # Connection strings & settings ├── types.md # Type definitions & data structures ├── errors.md # Exception types & error handling └── api-reference/ # Core API documentation ├── MongoClient-and-MongoClients.md ├── MongoDatabase.md ├── MongoCollection.md ├── FindIterable-and-Aggregation.md ├── Filters-Updates-Projections.md └── GridFS-and-Transactions.md ``` ``` -------------------------------- ### getWriteConcern() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets the write concern for the database. ```APIDOC ## getWriteConcern() ### Description Gets the write concern for the database. ### Method GET (Conceptual) ### Endpoint N/A (Method Call) ### Parameters None ### Return Type com.mongodb.WriteConcern ### Return Values The write concern configured for this database. ### Example ```java WriteConcern concern = db.getWriteConcern(); ``` ``` -------------------------------- ### Creating a GridFSBucket Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Demonstrates how to create a GridFSBucket instance for performing GridFS operations. You can use the default bucket name or specify a custom one. ```APIDOC ## Creating a GridFSBucket ### Description Creates a GridFSBucket instance for performing GridFS operations. You can use the default bucket name or specify a custom one. ### Code Example ```java import com.mongodb.client.MongoDatabase; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; // Assuming 'client' is an initialized MongoClient MongoDatabase db = client.getDatabase("mydb"); // Using default bucket name GridFSBucket bucket = GridFSBuckets.create(db); // Using a custom bucket name GridFSBucket customBucket = GridFSBuckets.create(db, "my_files"); ``` ``` -------------------------------- ### Create MongoClient with Settings and Driver Info Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Creates a new MongoClient instance with explicit settings and optional driver metadata. ```java MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("mongodb://localhost:27017")) .build(); MongoDriverInformation info = MongoDriverInformation.builder() .driverName("Spring Data MongoDB") .driverVersion("3.4.0") .build(); MongoClient client = MongoClients.create(settings, info); ``` -------------------------------- ### getReadPreference() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets the read preference for the database. ```APIDOC ## getReadPreference() ### Description Gets the read preference for the database. ### Method GET (Conceptual) ### Endpoint N/A (Method Call) ### Parameters None ### Return Type com.mongodb.ReadPreference ### Return Values The read preference configured for this database. ### Example ```java ReadPreference pref = db.getReadPreference(); System.out.println(pref.getName()); // Output: primary, secondary, etc. ``` ``` -------------------------------- ### getCodecRegistry() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets the codec registry for the database. ```APIDOC ## getCodecRegistry() ### Description Gets the codec registry for the database. ### Method GET (Conceptual) ### Endpoint N/A (Method Call) ### Parameters None ### Return Type org.bson.codecs.configuration.CodecRegistry ### Return Values The codec registry configured for this database. ### Example ```java CodecRegistry registry = db.getCodecRegistry(); ``` ``` -------------------------------- ### Sort and Limit Documents Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Example of an aggregation pipeline that filters documents, sorts them by creation date in descending order, and limits the results to the top 10. Results are collected into a list using into(). ```java List pipeline = Arrays.asList( new Document("$match", new Document("status", "active")), new Document("$sort", new Document("createdAt", -1)), new Document("$limit", 10) ); List topTen = collection.aggregate(pipeline) .into(new ArrayList<>()); ``` -------------------------------- ### first() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Gets the first aggregation result. Returns a nullable TDocument. ```APIDOC ## first() ### Description Gets the first aggregation result. ### Return Type TDocument (nullable) ### Example ```java Document result = (Document) collection.aggregate(pipeline) .first(); ``` ``` -------------------------------- ### Run bson-kotlin Tests and Checks Source: https://github.com/mongodb/mongo-java-driver/blob/main/bson-kotlin/AGENTS.md Execute the test suite and perform code checks for the bson-kotlin module using Gradle. ```bash ./gradlew :bson-kotlin:test ./gradlew :bson-kotlin:check ``` -------------------------------- ### Build and Test Kotlin Sync Driver Source: https://github.com/mongodb/mongo-java-driver/blob/main/driver-kotlin-sync/AGENTS.md Commands to build and run tests for the driver-kotlin-sync module. ```bash ./gradlew :driver-kotlin-sync:test ./gradlew :driver-kotlin-sync:check ``` -------------------------------- ### Single Replica Acknowledgment with Journaling Example Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Configures a write concern of '1' (acknowledgment from the primary) and enables journaling for enhanced durability. This is a common configuration for balancing performance and safety. ```text mongodb://localhost/?w=1&journal=true ``` -------------------------------- ### getCollection(String collectionName) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets a collection from this database using the default Document type. ```APIDOC ## getCollection(String collectionName) ### Description Gets a collection from this database using the default Document type. ### Method Signature `MongoCollection getCollection(String collectionName)` ### Parameters #### Path Parameters - **collectionName** (String) - Required - The name of the collection ### Return Type `MongoCollection` ### Throws - `IllegalArgumentException` - If collectionName is invalid ### Example ```java MongoCollection users = db.getCollection("users"); ``` ``` -------------------------------- ### Get Read Concern Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Retrieves the ReadConcern configured for this collection. This specifies the consistency guarantees for read operations. ```java ReadConcern getReadConcern() ``` -------------------------------- ### Get First Matching Document with first() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Use the `first()` method to retrieve only the first document that matches the query criteria. This is useful when you only need one result and want to avoid fetching unnecessary data. The returned document can be null if no match is found. ```java Document user = (Document) collection.find(Filters.eq("email", "alice@example.com")) .first(); if (user != null) { System.out.println(user.getString("name")); } ``` -------------------------------- ### Build and Test BSON Record Codec Source: https://github.com/mongodb/mongo-java-driver/blob/main/bson-record-codec/AGENTS.md Commands to build and test the bson-record-codec module using Gradle. ```bash ./gradlew :bson-record-codec:test ./gradlew :bson-record-codec:check ``` -------------------------------- ### Get Write Concern Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Retrieves the WriteConcern configured for this collection. This defines the acknowledgment guarantees for write operations. ```java WriteConcern getWriteConcern() ``` -------------------------------- ### getTimeout(TimeUnit timeUnit) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets the time limit for full execution of operations in the given time unit. ```APIDOC ## getTimeout(TimeUnit timeUnit) ### Description Gets the time limit for full execution of operations in the given time unit. ### Method GET (Conceptual) ### Endpoint N/A (Method Call) ### Parameters #### Path Parameters - **timeUnit** (TimeUnit) - Required - The time unit (MILLISECONDS, SECONDS, etc.) ### Return Type Long (nullable) ### Return Values - `null` - Uses default timeout mechanism - `0` - Infinite timeout - `> 0` - Time limit in given units ### Example ```java Long timeout = db.getTimeout(TimeUnit.MILLISECONDS); ``` ``` -------------------------------- ### Collect Reachability Metadata for Native Image Source: https://github.com/mongodb/mongo-java-driver/blob/main/graalvm-native-image-app/readme.md Cleans the project, runs the application with an agent to collect reachability metadata, and then copies the metadata. Perform this before building if the initial build fails. ```bash env JAVA_HOME="${JDK17}" ./gradlew clean && env JAVA_HOME=${JDK21_GRAALVM} ./gradlew -PincludeGraalvm -PjavaVersion=21 -Pagent :graalvm-native-image-app:run && env JAVA_HOME=${JDK21_GRAALVM} ./gradlew -PincludeGraalvm :graalvm-native-image-app:metadataCopy ``` -------------------------------- ### Get Read Concern Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Retrieves the read concern for the database. This specifies the durability guarantees for read operations. ```java ReadConcern concern = db.getReadConcern(); ``` -------------------------------- ### Build and Test Kotlin Extensions Source: https://github.com/mongodb/mongo-java-driver/blob/main/driver-kotlin-extensions/AGENTS.md Commands to build and test the driver-kotlin-extensions module. ```bash ./gradlew :driver-kotlin-extensions:test ./gradlew :driver-kotlin-extensions:check ``` -------------------------------- ### Get Write Concern Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Retrieves the write concern for the database. This defines the acknowledgment guarantees for write operations. ```java WriteConcern concern = db.getWriteConcern(); ``` -------------------------------- ### Run Native Application via Gradle Source: https://github.com/mongodb/mongo-java-driver/blob/main/graalvm-native-image-app/readme.md Builds the application if necessary and then runs it using Gradle. This command relies on stored reachability metadata. ```bash env JAVA_HOME="${JDK17}" ./gradlew -PincludeGraalvm -PjavaVersion=21 :graalvm-native-image-app:nativeRun ``` -------------------------------- ### Build and Test Legacy Driver Source: https://github.com/mongodb/mongo-java-driver/blob/main/driver-legacy/AGENTS.md Commands to build and test the legacy driver module using Gradle. ```bash ./gradlew :driver-legacy:test ./gradlew :driver-legacy:check ``` -------------------------------- ### Get Database Name Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Retrieves the name of the current MongoDB database. This is useful for verification or logging purposes. ```java MongoDatabase db = client.getDatabase("myapp"); System.out.println(db.getName()); // Output: myapp ``` -------------------------------- ### create(MongoClientSettings settings, MongoDriverInformation mongoDriverInformation) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Creates a new MongoClient instance with explicit settings and optional driver metadata. This overload offers the most flexibility in client creation. ```APIDOC ## create(MongoClientSettings settings, MongoDriverInformation mongoDriverInformation) ### Description Creates a new client with settings and optional driver metadata. ### Method `public static MongoClient create(MongoClientSettings settings, @Nullable MongoDriverInformation mongoDriverInformation)` ### Parameters #### Path Parameters - **settings** (MongoClientSettings) - Required - Complete client configuration - **mongoDriverInformation** (MongoDriverInformation) - Optional - Framework/library metadata ### Return Type `MongoClient` ### Example ```java MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("mongodb://localhost:27017")) .build(); MongoDriverInformation info = MongoDriverInformation.builder() .driverName("Spring Data MongoDB") .driverVersion("3.4.0") .build(); MongoClient client = MongoClients.create(settings, info); ``` ``` -------------------------------- ### estimatedDocumentCount(EstimatedDocumentCountOptions options) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Gets an estimated document count with specified options, such as maxTimeMS, to control the estimation process. ```APIDOC ## estimatedDocumentCount(EstimatedDocumentCountOptions options) ### Description Gets estimated count with options. ### Method N/A (Java method) ### Endpoint N/A (Java method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **options** (EstimatedDocumentCountOptions) - Required - Options (maxTimeMS) ### Return Type long ### Example None provided in source. ``` -------------------------------- ### estimatedDocumentCount() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Gets an estimate of the document count using collection metadata. This method is faster but provides an approximate count. ```APIDOC ## estimatedDocumentCount() ### Description Gets an estimate of document count using collection metadata (faster but approximate). ### Method N/A (Java method) ### Endpoint N/A (Java method) ### Parameters None ### Return Type long ### Example ```java long estimate = collection.estimatedDocumentCount(); ``` ``` -------------------------------- ### Configure Server Settings Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Set parameters for server heartbeat frequency. ```java .applyToServerSettings(builder -> builder .heartbeatFrequencyMS(10000) .minHeartbeatFrequencyMS(500)) ``` -------------------------------- ### Get First Aggregation Result Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Retrieves only the first document from an aggregation pipeline. Use when you only need a single result. ```java Document result = (Document) collection.aggregate(pipeline) .first(); ``` -------------------------------- ### Delete Documents in MongoDB Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/README.md Code examples for deleting single documents, all matching documents, and atomic find-and-delete operations. ```java // Delete single DeleteResult result = collection.deleteOne(filter); ``` ```java // Delete all matching collection.deleteMany(filter); ``` ```java // Find and delete atomically Document deleted = collection.findOneAndDelete(filter); ``` -------------------------------- ### create(MongoClientSettings settings) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Creates a new MongoClient instance with explicit MongoClientSettings. This provides fine-grained control over all client configurations. ```APIDOC ## create(MongoClientSettings settings) ### Description Creates a new client with explicit `MongoClientSettings`. ### Method `public static MongoClient create(MongoClientSettings settings)` ### Parameters #### Path Parameters - **settings** (MongoClientSettings) - Required - Complete client configuration ### Return Type `MongoClient` ### Example ```java MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("mongodb://localhost:27017")) .retryWrites(true) .build(); MongoClient client = MongoClients.create(settings); ``` ``` -------------------------------- ### Get Collection Namespace Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Retrieves the namespace (database.collection) of the current collection. This is useful for identifying the collection within the MongoDB instance. ```java MongoNamespace ns = collection.getNamespace(); System.out.println(ns); // Output: mydb.users ``` -------------------------------- ### Run Scala Async Driver Static Checks and Tests Source: https://github.com/mongodb/mongo-java-driver/blob/main/driver-scala/AGENTS.md Perform static checks and run tests for the Scala async driver using Gradle with the default Scala version. ```bash ./gradlew :driver-scala:scalaCheck ``` -------------------------------- ### getCollection(String collectionName, Class documentClass) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Gets a collection with a specific document class for automatic BSON mapping. ```APIDOC ## getCollection(String collectionName, Class documentClass) ### Description Gets a collection with a specific document class for automatic BSON mapping. ### Method Signature ` MongoCollection getCollection(String collectionName, Class documentClass)` ### Parameters #### Path Parameters - **collectionName** (String) - Required - The name of the collection - **documentClass** (Class) - Required - The class to map documents to ### Return Type `MongoCollection` ### Example ```java class User { public String id; public String name; public String email; } MongoCollection users = db.getCollection("users", User.class); ``` ``` -------------------------------- ### Configure Spotless for Scala 3 Source: https://github.com/mongodb/mongo-java-driver/blob/main/bson-scala/README.md Configures Spotless to use Scala 3 specific formatting rules for files within the '**/scala-3/**' directory. ```kotlin if (scalaVersion.equals("3")) { spotless { scala { clearSteps() target("**/scala-3/**") scalafmt("3.10.7").configFile(rootProject.file("config/scala/scalafmt-3.conf")) } } } ``` -------------------------------- ### Get Default Document Collection Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Retrieves a collection with the default Document type. Use this when you don't need custom mapping. ```java MongoCollection users = db.getCollection("users"); ``` -------------------------------- ### Filtering and Projection Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Example of an aggregation pipeline that filters documents based on a score and projects specific fields (name and score). ```APIDOC ## Filtering and Projection ### Description Filters documents with a score greater than or equal to 80 and projects only the name and score fields. ### Example ```java List pipeline = Arrays.asList( new Document("$match", new Document("score", new Document("$gte", 80))), new Document("$project", new Document("name", 1) .append("score", 1) .append("_id", 0)) ); List results = collection.aggregate(pipeline) .into(new ArrayList<>()); ``` ``` -------------------------------- ### Checkout 3.0.x Branch Source: https://github.com/mongodb/mongo-java-driver/wiki/Getting-Started:-IntelliJ-Setup Navigate into the cloned project directory and switch to the 3.0.x branch to work with the specified version of the Java Driver code. ```bash cd mongo-java-driver git checkout 3.0.x ``` -------------------------------- ### Run Built Native Application Source: https://github.com/mongodb/mongo-java-driver/blob/main/graalvm-native-image-app/readme.md Executes the application that has been compiled into a native executable. ```bash ./graalvm-native-image-app/build/native/nativeCompile/NativeImageApp ``` -------------------------------- ### Grouping and Counting Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Example of a common aggregation pattern for grouping documents by a field and counting them, along with calculating the average price. ```APIDOC ## Grouping and Counting ### Description Demonstrates grouping documents by category, counting them, and calculating the average price for active documents. ### Example ```java List pipeline = Arrays.asList( new Document("$match", new Document("status", "active")), new Document("$group", new Document("_id", "$category") .append("count", new Document("$sum", 1)) .append("avgPrice", new Document("$avg", "$price"))) ); collection.aggregate(pipeline) .forEach(doc -> System.out.println(doc)); ``` ``` -------------------------------- ### Run Scala Async Driver Tests Source: https://github.com/mongodb/mongo-java-driver/blob/main/driver-scala/AGENTS.md Execute all tests for the Scala async driver using Gradle. This command runs static checks and tests for the default Scala version. ```bash ./gradlew :driver-scala:test ``` -------------------------------- ### Update Documents in MongoDB Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/README.md Examples for updating single fields, multiple fields, all matching documents, and atomic find-and-update operations. ```java // Update single field UpdateResult result = collection.updateOne( filter, Updates.set("fieldName", value) ); ``` ```java // Update multiple fields collection.updateOne(filter, Updates.combine( Updates.set("field1", value1), Updates.inc("field2", 1), Updates.unset("field3") )); ``` ```java // Update all matching collection.updateMany(filter, update); ``` ```java // Find and update atomically Document updated = collection.findOneAndUpdate( filter, update, new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER) ); ``` -------------------------------- ### Configure SSL/TLS Settings Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Enable or disable SSL/TLS and control hostname validation. ```java .applyToSslSettings(builder -> builder .enabled(true) .invalidHostNameAllowed(false)) ``` -------------------------------- ### Find Documents in MongoDB Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/README.md Examples for finding documents with various criteria, including filters, projections, sorting, limiting, and pagination. ```java // All documents for (Document doc : collection.find()) { } ``` ```java // With filter collection.find(Filters.eq("status", "active")); ``` ```java // Complex filter collection.find(Filters.and( Filters.gte("price", 100), Filters.lte("price", 500) )); ``` ```java // Project specific fields collection.find() .projection(Projections.include("name", "price")); ``` ```java // Sort and limit collection.find() .sort(Sorts.descending("price")) .limit(10); ``` ```java // Pagination int pageSize = 20; int page = 2; collection.find() .skip(page * pageSize) .limit(pageSize); ``` -------------------------------- ### Count Documents Accurately Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Use `countDocuments()` to get an accurate count of all documents in a collection. This method can be slower than `estimatedDocumentCount()` for large collections. ```java long count = collection.countDocuments(); ``` -------------------------------- ### Build Native Image with Reachability Metadata Source: https://github.com/mongodb/mongo-java-driver/blob/main/graalvm-native-image-app/readme.md Builds the application using GraalVM native image compilation, relying on pre-defined reachability metadata. ```bash env JAVA_HOME="${JDK17}" ./gradlew -PincludeGraalvm -PjavaVersion=21 :graalvm-native-image-app:nativeCompile ``` -------------------------------- ### Create GridFSBucket Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Instantiate a GridFSBucket for file operations. You can use the default bucket name or specify a custom one. ```java MongoDatabase db = client.getDatabase("mydb"); GridFSBucket bucket = GridFSBuckets.create(db); // With custom bucket name GridFSBucket customBucket = GridFSBuckets.create(db, "my_files"); ``` -------------------------------- ### Get Read Preference Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Retrieves the ReadPreference configured for this collection. This determines which MongoDB replica set member is used for read operations. ```java ReadPreference getReadPreference() ``` -------------------------------- ### Get Document Class Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Retrieves the Java class representing the documents stored in this collection. This is determined by the generic type parameter of MongoCollection. ```java Class clazz = collection.getDocumentClass(); ``` -------------------------------- ### Create MongoClient with Connection String and Driver Info Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Creates a new MongoClient instance using a connection string and optional driver metadata for server logs. ```java MongoDriverInformation driverInfo = MongoDriverInformation.builder() .driverName("MyFramework") .driverVersion("1.0.0") .build(); ConnectionString connStr = new ConnectionString("mongodb://localhost:27017"); MongoClient client = MongoClients.create(connStr, driverInfo); ``` -------------------------------- ### Get Deleted Count from DeleteResult Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/types.md Retrieves the number of documents deleted by a delete operation. This is a straightforward way to confirm the outcome of a deletion. ```java DeleteResult result = collection.deleteMany(filter); System.out.println("Deleted: " + result.getDeletedCount()); ``` -------------------------------- ### create() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Creates a new MongoClient instance using the default connection string 'mongodb://localhost'. This is a convenient method for quick connections to a local MongoDB instance. ```APIDOC ## create() ### Description Creates a new client with the default connection string `mongodb://localhost`. ### Method `public static MongoClient create()` ### Parameters This method does not accept any parameters. It connects to `localhost:27017` by default. ### Return Type `MongoClient` ### Example ```java MongoClient client = MongoClients.create(); MongoDatabase db = client.getDatabase("mydb"); ``` ``` -------------------------------- ### Get Cluster Description Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Retrieves the current cluster description without blocking. The description might be stale or show a connecting state. ```java MongoClient client = MongoClients.create("mongodb://localhost:27017"); ClusterDescription clusterDesc = client.getClusterDescription(); System.out.println("Cluster type: " + clusterDesc.getClusterType()); System.out.println("Servers: " + clusterDesc.getServerDescriptions().size()); ``` -------------------------------- ### Scala BSON Directory Layout Source: https://github.com/mongodb/mongo-java-driver/blob/main/bson-scala/README.md Illustrates the directory structure for organizing Scala code based on version specificity within the bson-scala project. ```text src/main/ ├── scala/ # Shared code (all Scala versions) ├── scala-2/ # Scala 2 only (2.11, 2.12 and 2.13) ├── scala-2.13/ # Scala 2.13 only ├── scala-2.13-/ # Scala 2.12 & 2.11 ├── scala-3/ # Scala 3 only ``` -------------------------------- ### Configure Cluster Settings Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/configuration.md Use this to configure cluster-specific settings like server selection timeout, local threshold, and replica set name. ```java .applyToClusterSettings(builder -> builder .serverSelectionTimeoutMS(30000) .localThresholdMS(15) .description("My Cluster") .directConnection(false) .replicaSetName("rs0") .addClusterListener(myClusterListener)) ``` -------------------------------- ### Get Custom Document Collection Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Retrieves a collection with a specific document class for automatic BSON mapping. Define a class to represent your documents. ```java class User { public String id; public String name; public String email; } MongoCollection users = db.getCollection("users", User.class); ``` -------------------------------- ### Get Read Preference Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Retrieves the read preference configured for the database. This determines which MongoDB replica set member(s) read operations are sent to. ```java ReadPreference pref = db.getReadPreference(); System.out.println(pref.getName()); // Output: primary, secondary, etc. ``` -------------------------------- ### createIndex(Bson keys, CreateIndexOptions options) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Creates an index with specified options. ```APIDOC ## createIndex(Bson keys, CreateIndexOptions options) ### Description Creates an index with options. ### Method Signature ```java String createIndex(Bson keys, CreateIndexOptions options) ``` ### Parameters #### Path Parameters - **keys** (Bson) - Required - The index specification - **options** (CreateIndexOptions) - Required - Options (unique, sparse, etc.) ### Return Type String ### Request Example ```java String indexName = collection.createIndex( new Document("email", 1), new CreateIndexOptions().unique(true).sparse(true) ); ``` ``` -------------------------------- ### Get Codec Registry Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Retrieves the codec registry associated with the database. This registry handles the encoding and decoding of BSON documents to Java objects. ```java CodecRegistry registry = db.getCodecRegistry(); ``` -------------------------------- ### startTransaction() Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/GridFS-and-Transactions.md Begins a transaction on the current session. Throws an IllegalStateException if a transaction is already active. ```APIDOC ## startTransaction() Begins a transaction. ### Method Signature ```java void startTransaction() ``` ### Return Type void ### Throws `IllegalStateException` if transaction already active ### Notes Automatically aborted if connection drops ``` -------------------------------- ### Run BSON Module Tests Source: https://github.com/mongodb/mongo-java-driver/blob/main/bson/AGENTS.md Execute tests for the BSON module using Gradle. This command runs all unit and integration tests for the BSON library. ```bash ./gradlew :bson:test ``` -------------------------------- ### runCommand(Bson command) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Executes a database command with primary read preference. ```APIDOC ## runCommand(Bson command) ### Description Executes a database command with primary read preference. ### Method Signature `Document runCommand(Bson command)` ### Parameters #### Path Parameters - **command** (Bson) - Required - The command document (e.g., from `new Document()`) ### Return Type `Document` ### Example ```java Document result = db.runCommand(new Document("ping", 1)); System.out.println(result.getDouble("ok")); // 1.0 for success ``` ``` -------------------------------- ### Create Index with Options Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Use to create an index with specific options such as unique or sparse. Returns the name of the created index. ```java String indexName = collection.createIndex( new Document("email", 1), new CreateIndexOptions().unique(true).sparse(true) ); ``` -------------------------------- ### Configure AggregateIterable Hint Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/FindIterable-and-Aggregation.md Specifies an index to be used by the aggregation query. This can help optimize performance by guiding the query planner to a specific index. ```java collection.aggregate(pipeline) .hint(new Document("fieldName", 1)); ``` -------------------------------- ### Create MongoClient with MongoClientSettings Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoClient-and-MongoClients.md Creates a new MongoClient instance with explicit MongoClientSettings for detailed configuration. ```java MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("mongodb://localhost:27017")) .retryWrites(true) .build(); MongoClient client = MongoClients.create(settings); ``` -------------------------------- ### Build and Test Synchronous Driver Source: https://github.com/mongodb/mongo-java-driver/blob/main/driver-sync/AGENTS.md Commands to build and run tests for the driver-sync module. Use these to ensure code changes meet quality standards. ```bash ./gradlew :driver-sync:test ./gradlew :driver-sync:check ``` -------------------------------- ### Get Operation Timeout Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoCollection.md Retrieves the time limit for operation execution in the specified time unit. This method is marked as Alpha and may be subject to change. ```java @Alpha(Reason.CLIENT) @Nullable Long getTimeout(TimeUnit timeUnit) ``` -------------------------------- ### runCommand(Bson command, ReadPreference readPreference) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/MongoDatabase.md Executes a database command with a specific read preference. ```APIDOC ## runCommand(Bson command, ReadPreference readPreference) ### Description Executes a database command with a specific read preference. ### Method Signature `Document runCommand(Bson command, ReadPreference readPreference)` ### Parameters #### Path Parameters - **command** (Bson) - Required - The command document - **readPreference** (ReadPreference) - Required - The read preference for command execution ### Return Type `Document` ### Example ```java Document result = db.runCommand( new Document("dbStats", 1), ReadPreference.secondary() ); ``` ``` -------------------------------- ### Create 'exists' Filter (Field Not Exists) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/Filters-Updates-Projections.md Use this filter to match documents where a specific field does not exist. The example checks if the 'deletedAt' field is absent. ```java Bson filter = Filters.exists("deletedAt", false); // Field should not exist ``` -------------------------------- ### Create 'exists' Filter (Field Exists) Source: https://github.com/mongodb/mongo-java-driver/blob/main/_autodocs/api-reference/Filters-Updates-Projections.md Use this filter to match documents where a specific field is present. The example checks for the existence of the 'middleName' field. ```java Bson filter = Filters.exists("middleName"); ``` ```javascript { "middleName": { "$exists": true } } ```