Class Collection<T>

Type Parameters:
T - Java bean to unmarshall documents for collection.
All Implemented Interfaces:
CommandRunner

public class Collection<T> extends AbstractCommandRunner<CollectionOptions>
A Data API collection, the main object to interact with the Data API, especially for DDL operations.

A Collection is spawned from a Database object, from which it inherits the details on how to reach the API server (endpoint, authentication). A Collection has a name, which is its unique identifier for a namespace and options to specialize the usage as vector collections or advanced indexing parameters.

A Collection is typed object designed to work both with default @Document (wrapper for a Map) and application plain old java objects (pojo). The serialization is performed with Jackson and application beans can be annotated.

All features are provided in synchronous and asynchronous flavors.

Example usage:

 
 // Given a Database
 Database db = new DataAPIClient("token").getDatabase("api_endpoint");

 // Initialization with no POJO
 Collection<Document> collection = db.getCollection("collection1");

 // Initialization with POJO
 Collection<MyBean> collection = db.getCollection("collection1", MyBean.class);
 
 
  • Field Details Link icon

  • Constructor Details Link icon

    • Collection Link icon

      public Collection(Database db, String collectionName, CollectionOptions collectionOptions, Class<T> documentClass)
      Constructs an instance of a collection within the specified database. This constructor initializes the collection with a given name and associates it with a specific class type that represents the schema of documents within the collection. This setup is designed for CRUD (Create, Read, Update, Delete) operations.
      Parameters:
      db - The Database instance representing the client's namespace for HTTP communication with the database. It encapsulates the configuration and management of the database connection, ensuring that operations on this collection are executed within the context of this database.
      collectionName - A String that uniquely identifies the collection within the database. This name is used to route operations to the correct collection and should adhere to the database's naming conventions.
      collectionOptions - the options to apply to the command operation. If left blank the default collection
      documentClass - The Class object representing the schema of documents stored

      Example usage:

       
       // Given a client
       DataAPIClient client = new DataAPIClient("token");
       // Given a database
       Database myDb = client.getDatabase("myDb");
       // Initialize a collection with a working class
       Collection<MyDocumentClass> myCollection = new Collection<>(myDb, "myCollectionName", MyDocumentClass.class);
       
       
  • Method Details Link icon

    • getKeyspaceName Link icon

      public String getKeyspaceName()
      Retrieves the name of the parent keyspace associated with this collection. A keyspace in this context typically refers to a higher-level categorization or grouping mechanism within the database that encompasses one or more collections. This method allows for identifying the broader context in which this collection exists, which can be useful for operations requiring knowledge of the database structure or for dynamic database interaction patterns.
      Returns:
      A String representing the name of the parent keyspace of the current collection. This name serves as an identifier for the keyspace and can be used to navigate or query the database structure.

      Example usage:

       
       Collection myCollection = ... // assume myCollection is already initialized
       String keyspaceName = myCollection.getKeyspaceName();
       System.out.println("The collection belongs to the keyspace: " + namespaceName);
       
       
    • getDefinition Link icon

      public CollectionDefinition getDefinition()
      Retrieves the full definition of the collection, encompassing both its name and its configuration options. This comprehensive information is encapsulated in a CollectionInfo object, providing access to the collection's metadata and settings.

      The returned CollectionInfo includes details such as the collection's name, which serves as its unique identifier within the database, and a set of options that describe its configuration. These options may cover aspects like indexing preferences, read/write permissions, and other customizable settings that were specified at the time of collection creation.

      Example usage:

       
       // Given a collection
       DataApiCollection<Document> collection;
       // Access its Definition
       CollectionDefinition definition = collection.getDefinition();
       System.out.println("Name=" + definition.getName());
       CollectionOptions options = definition.getOptions();
       if (options != null) {
         // Operations based on collection options
       }
       
       
      Returns:
      A CollectionInfo object containing the full definition of the collection, including its name and configuration options. This object provides a comprehensive view of the collection's settings and identity within the database.
    • insertOne Link icon

      public final CollectionInsertOneResult insertOne(T document)
      Inserts a single document into the collection as an atomic operation, ensuring that the document is added in a single, indivisible step.

      Note: The document can optionally include an _id property, which serves as its unique identifier within the collection. If the _id property is provided and it matches the _id of an existing document in the collection, the insertion will fail and an error will be raised. This behavior ensures that each document in the collection has a unique identifier. If the _id property is not provided, the server will automatically generate a unique _id for the document, ensuring its uniqueness within the collection.

      The `_id` can be of multiple types, by default it can be any json scalar String, Number, $date. But at the collection definition level you can enforce property `defaultId` to work with specialize ids.

      • If defaultId is set to uuid, ids will be uuid v4 UUID
      • If defaultId is set to objectId, ids will be an ObjectId
      • If defaultId is set to uuidv6, ids will be an UUIDv6
      • If defaultId is set to uuidv7, ids will be an UUIDv7

      The method returns an InsertOneResult object, which provides details about the outcome of the insertion operation. This object can be used to verify the success of the operation and to access the _id of the inserted document, whether it was provided explicitly or generated automatically.

      Parameters:
      document - the document to be inserted into the collection. This parameter should represent the document in its entirety. The _id field is optional and, if omitted, will be automatically generated.
      Returns:
      An InsertOneResult object that contains information about the result of the insertion operation, including the _id of the newly inserted document.

      Example usage:

       
       // Create a document without id.
       Document newDocument = new Document("name", "John Doe").append("age", 30);
       InsertOneResult result = collection.insertOne(newDocument);
       System.out.println("(generated) document id: " + result.getInsertedId());
      
       // Provide a document id
       Document doc2 = Document.create("doc2").append("name", "John Doe").append("age", 30);
       InsertOneResult result = collection.insertOne(doc2);
       result.getInsertedId(); // will be "doc2"
      
       // More way to provide to populate ids.
       Document doc3 = new Document("doc3");
       Document doc4 = new Document().id("doc4");
       Document doc5 = new Document().append("_id", "doc5");
       
       
    • insertOne Link icon

      public final CollectionInsertOneResult insertOne(T document, CollectionInsertOneOptions collectionInsertOneOptions)
      Inserts a single document into the collection as an atomic operation, ensuring that the document is added in a single, indivisible step.

      Note: The document can optionally include an _id property, which serves as its unique identifier within the collection. If the _id property is provided and it matches the _id of an existing document in the collection, the insertion will fail and an error will be raised. This behavior ensures that each document in the collection has a unique identifier. If the _id property is not provided, the server will automatically generate a unique _id for the document, ensuring its uniqueness within the collection.

      The `_id` can be of multiple types, by default it can be any json scalar String, Number, $date. But at the collection definition level you can enforce property `defaultId` to work with specialize ids.

      • If defaultId is set to uuid, ids will be uuid v4 UUID
      • If defaultId is set to objectId, ids will be an ObjectId
      • If defaultId is set to uuidv6, ids will be an UUIDv6
      • If defaultId is set to uuidv7, ids will be an UUIDv7

      The method returns an InsertOneResult object, which provides details about the outcome of the insertion operation. This object can be used to verify the success of the operation and to access the _id of the inserted document, whether it was provided explicitly or generated automatically.

      Parameters:
      document - the document to be inserted into the collection. This parameter should represent the document in its entirety. The _id field is optional and, if omitted, will be automatically generated.
      collectionInsertOneOptions - the options to apply to the insert operation. If left blank the default collection options will be used. If collection option is blank DataAPIOptions will be used.
      Returns:
      An InsertOneResult object that contains information about the result of the insertion operation, including the _id of the newly inserted document.

      Example usage:

       
       // Create a document without id.
       Document newDocument = new Document("name", "John Doe").append("age", 30);
       InsertOneResult result = collection.insertOne(newDocument);
       System.out.println("(generated) document id: " + result.getInsertedId());
      
       // Provide a document id
       Document doc2 = Document.create("doc2").append("name", "John Doe").append("age", 30);
       InsertOneResult result = collection.insertOne(doc2);
       result.getInsertedId(); // will be "doc2"
      
       // More way to provide to populate ids.
       Document doc3 = new Document("doc3");
       Document doc4 = new Document().id("doc4");
       Document doc5 = new Document().append("_id", "doc5");
       
       
    • insertOneAsync Link icon

      public final CompletableFuture<CollectionInsertOneResult> insertOneAsync(T document)
      Asynchronously inserts a single document into the collection. This method provides the same functionality as insertOne(Object), but it operates asynchronously, returning a CompletableFuture that will be completed with the insertion result. Utilizing this method is beneficial for non-blocking operations, allowing other tasks to proceed while the document insertion is being processed.

      The asynchronous operation ensures that your application can remain responsive, making this method ideal for applications requiring high throughput or for operations that do not need immediate completion confirmation.

      For details on the behavior, parameters, and return type, refer to the documentation of the synchronous insertOne(Object) method. This method inherits all the properties and behaviors of its synchronous counterpart, including error handling and the generation or requirement of the _id field.

      Parameters:
      document - The document to be inserted into the collection. The specifications regarding the document structure and the _id field are the same as described in insertOne(Object).
      Returns:
      A CompletableFuture that, upon completion, contains the result of the insert operation as an CollectionInsertOneResult. The completion may occur with a result in case of success or with an exception in case of failure.

      Example usage:

       
       // Asynchronously inserting a document
       Document newDocument = new Document().append("name", "Async User").append("age", 34);
       CompletableFuture<InsertOneResult> futureResult = collection.insertOneAsync(newDocument);
       futureResult.thenAccept(result -> System.out.println("Inserted document id: " + result.getInsertedId()))
                   .exceptionally(error -> { System.err.println("Insertion failed: " + error.getMessage()); return null; });
       
       
    • insertOneAsync Link icon

      public final CompletableFuture<CollectionInsertOneResult> insertOneAsync(T document, CollectionInsertOneOptions options)
      Asynchronous implementation of insertOne(Object, CollectionInsertOneOptions).
      Parameters:
      document - document to insert
      options - the options to apply to the insert operation. If left blank the default collection options will be used. If collection option is blank DataAPIOptions will be used.
      Returns:
      result for insertion
    • insertMany Link icon

      public CollectionInsertManyResult insertMany(List<? extends T> documents, CollectionInsertManyOptions options)
      Inserts a batch of documents into the collection concurrently, optimizing the insertion process for large datasets. This method provides a powerful mechanism to insert multiple documents with customizable concurrency levels and batch sizes, while also ensuring error handling and performance optimization.

      Validation: The method validates the input documents list for nullity and emptiness. It also checks each document within the list to ensure none are null, throwing an IllegalArgumentException if these conditions are not met.

      Concurrency and Ordering: If concurrent insertion is requested with ordered inserts (via options), the method throws an IllegalArgumentException, as ordered operations cannot be performed concurrently.

      Chunk Size and Maximum Insertions: The method checks if the specified chunk size exceeds the maximum number of documents allowed for insertion in a single operation, throwing an IllegalArgumentException if this limit is breached.

      Documents are then split into chunks, each processed in parallel, according to the concurrency level specified in options. The results of these insertions are aggregated into a single CollectionInsertManyResult.

      Timeout Handling: The method attempts to complete all insertion tasks within the specified timeout. If tasks do not complete in time, a TimeoutException is thrown.

      Error Handling: Exceptions encountered during insertion or result aggregation are captured, and a RuntimeException is thrown, indicating an issue with merging results into a single CollectionInsertManyResult.

      Example usage: Inserting a list of 100 documents

       
       InsertManyOptions options = InsertManyOptions.builder()
         .ordered(false)     // required for concurrent processing
         .withConcurrency(5) // recommended
         .withChunkSize(20)  // maximum chunk size is 20
         .withTimeout(100)   // global timeout
         .build();
       List<Document> documents = new ArrayList<>();
       for (int i = 0; i < 100; i++) {
           documents.add(new Document().append("key" + i, "value" + i));
       }
       InsertManyResult result = collection.insertMany(documents, options);
       System.out.println("Inserted document count: " + result.getInsertedIds().size());
       
       

      Performance Monitoring: Logs the total response time for the insert many operation, aiding in performance analysis and optimization efforts.

      Parameters:
      documents - A list of documents to be inserted. Must not be null or empty, and no document should be null.
      options - Detailed options for the insert many operation, including concurrency level, chunk size, and whether the inserts should be ordered.
      Returns:
      An CollectionInsertManyResult object containing the IDs of all successfully inserted documents.
      Throws:
      IllegalArgumentException - if the documents list is null or empty, any document is null, or if the options specified are invalid.
      RuntimeException - if there is an error in merging the results of concurrent insertions.
    • insertManyAsync Link icon

      public CompletableFuture<CollectionInsertManyResult> insertManyAsync(List<? extends T> documents, CollectionInsertManyOptions options)
      Asynchronously inserts a batch of documents into the collection with customizable insertion options. This method is the asynchronous counterpart to insertMany(List, CollectionInsertManyOptions), allowing for non-blocking operations. It employs default or specified CollectionInsertManyOptions to optimize the insertion process for large datasets, utilizing concurrency and batch processing to enhance performance.

      Utilizing CompletableFuture, this method facilitates the insertion of multiple documents without halting the execution of your application, making it well-suited for applications requiring high throughput or responsiveness. For scenarios necessitating specific insertion behaviors, such as concurrency levels and chunk sizes, the provided options parameter enables fine-tuned control over the asynchronous operation.

      This method inherits all the validation, chunking, and result aggregation logic from its synchronous counterpart, ensuring consistent behavior and error handling, while extending functionality to support asynchronous execution patterns.

      Usage: Recommended for inserting large numbers of documents or when the application's workflow benefits from non-blocking operations. For simpler use cases or default settings, the overload without options provides a more straightforward approach.

      Example usage: Asynchronously inserting a list of documents with custom options.

       
       List<Document> documents = new ArrayList<>();
       for (int i = 0; i < 100; i++) {
           documents.add(new Document().append("key" + i, "value" + i));
       }
       InsertManyOptions options = new InsertManyOptions().setConcurrency(5).setChunkSize(20);
       CompletableFuture<InsertManyResult> futureResult = collection.insertManyAsync(documents, options);
       futureResult.thenAccept(result -> System.out.println("Inserted document count: " + result.getInsertedIds().size()))
                   .exceptionally(error -> { System.err.println("Insertion failed: " + error.getMessage()); return null; });
       
       
      Parameters:
      documents - A list of documents to be inserted. The list must not be null or empty, and no document should be null.
      options - Detailed options for the insert many operation, allowing customization of concurrency level, chunk size, and insertion order.
      Returns:
      A CompletableFuture that, upon completion, contains the CollectionInsertManyResult indicating the outcome of the insert operation. The future may complete normally with the insertion result or exceptionally in case of an error.
      Throws:
      IllegalArgumentException - if the documents list is null or empty, or if any document is null.
    • insertMany Link icon

      public CollectionInsertManyResult insertMany(List<? extends T> documents)
      Inserts a batch of documents into the collection using default insertion options. This method is a simplified version of insertMany(List, CollectionInsertManyOptions), intended for use cases where default settings for concurrency, chunk size, and insertion order are sufficient. It provides an efficient way to insert multiple documents concurrently, optimizing the insertion process with predefined settings.

      The default CollectionInsertManyOptions used by this method assumes non-concurrent (sequential) insertion, with no specific chunk size or timeout constraints. This is suitable for general use cases where the simplicity of invocation is prioritized over the customization of insertion parameters. For more advanced control over the insertion process, including the ability to specify concurrency levels, chunk sizes, and operation timeouts, use the overloaded insertMany(List, CollectionInsertManyOptions) method.

      This method leverages the same underlying insertion logic as its overloaded counterpart, ensuring consistent behavior and error handling. It automatically handles validation of the input documents list, chunking of documents based on default settings, and aggregation of insertion results into a single CollectionInsertManyResult.

      Usage: Ideal for inserting a collection of documents without the need for custom insertion options. Simplifies the insertion process for basic use cases.

      Parameters:
      documents - A list of documents to be inserted. Must not be null or empty, and no document should be null.
      Returns:
      An CollectionInsertManyResult object containing the IDs of all successfully inserted documents.
      Throws:
      IllegalArgumentException - if the documents list is null or empty, or if any document is null.
      RuntimeException - if there is an error in merging the results of concurrent insertions.
    • insertMany Link icon

      @SafeVarargs public final CollectionInsertManyResult insertMany(T... documents)
      Inserts a batch of documents into the collection using default insertion options. This method is a simplified version of insertMany(List, CollectionInsertManyOptions), intended for use cases where default settings for concurrency, chunk size, and insertion order are sufficient. It provides an efficient way to insert multiple documents concurrently, optimizing the insertion process with predefined settings.

      The default CollectionInsertManyOptions used by this method assumes non-concurrent (sequential) insertion, with no specific chunk size or timeout constraints. This is suitable for general use cases where the simplicity of invocation is prioritized over the customization of insertion parameters. For more advanced control over the insertion process, including the ability to specify concurrency levels, chunk sizes, and operation timeouts, use the overloaded insertMany(List, CollectionInsertManyOptions) method.

      This method leverages the same underlying insertion logic as its overloaded counterpart, ensuring consistent behavior and error handling. It automatically handles validation of the input documents list, chunking of documents based on default settings, and aggregation of insertion results into a single CollectionInsertManyResult.

      Usage: Ideal for inserting a collection of documents without the need for custom insertion options. Simplifies the insertion process for basic use cases.

      Parameters:
      documents - A list of documents to be inserted. Must not be null or empty, and no document should be null.
      Returns:
      An CollectionInsertManyResult object containing the IDs of all successfully inserted documents.
      Throws:
      IllegalArgumentException - if the documents list is null or empty, or if any document is null.
      RuntimeException - if there is an error in merging the results of concurrent insertions.
    • insertManyAsync Link icon

      public CompletableFuture<CollectionInsertManyResult> insertManyAsync(List<? extends T> documents)
      Asynchronously inserts a batch of documents into the collection using default insertion options. This method provides an asynchronous alternative to insertMany(List), facilitating non-blocking operations while employing a simplified insertion process suited for general use cases.

      Utilizing CompletableFuture, this method allows the insertion of multiple documents without interrupting the application's execution flow. It is particularly useful in scenarios requiring high throughput or when maintaining application responsiveness is critical. The default insertion settings are applied, simplifying the operation and making it accessible for basic insertion needs without the necessity for custom configuration.

      This method inherits the core logic and validations from its synchronous counterpart, ensuring consistent behavior and error handling. It automatically manages the input documents list, applying default options for chunking and concurrency, and aggregates the results into a single CollectionInsertManyResult asynchronously.

      Usage: Ideal for applications that benefit from asynchronous document insertion, especially when inserting a large number of documents under default settings. This method simplifies asynchronous batch insertions, making it straightforward to integrate into existing workflows.

      Example usage: Asynchronously inserting a list of 100 documents using default options.

       
       List<Document> documents = new ArrayList<>();
       for (int i = 0; i < 100; i++) {
           documents.add(new Document().append("key" + i, "value" + i));
       }
       CompletableFuture<InsertManyResult> futureResult = collection.insertManyAsync(documents);
       futureResult.thenAccept(result -> System.out.println("Inserted document count: " + result.getInsertedIds().size()))
                   .exceptionally(error -> { System.err.println("Insertion failed: " + error.getMessage()); return null; });
       
       
      Parameters:
      documents - A list of documents to be inserted. Must not be null or empty, and no document within the list should be null.
      Returns:
      A CompletableFuture that, upon completion, contains the CollectionInsertManyResult indicating the outcome of the insert operation. The future may complete with the insertion results or exceptionally in case of an error.
      Throws:
      IllegalArgumentException - if the documents list is null or empty, or if any document is null.
    • findOne Link icon

      public Optional<T> findOne(Filter filter)
      Attempts to find a single document within the collection that matches the given filter criteria. This method efficiently locates the first document that fulfills the specified conditions, making it an optimal choice for queries where a unique identifier or specific characteristics are used to identify a document. Its efficiency stems from the ability to halt the search as soon as a matching document is found, potentially avoiding a full collection scan.

      Utilizing a Filter instance to articulate the search criteria, this method sifts through the collection to find a document that aligns with the provided conditions. The filter defines the parameters that a document must satisfy to be deemed a match, encompassing a wide range of possible attributes and values specific to the document structure and contents within the collection.

      In cases where the search does not yield a matching document, this method returns an empty Optional, signifying the absence of a compatible document. This design choice facilitates more graceful error handling, allowing callers to easily distinguish between the presence and absence of a match without resorting to exception handling for non-existent documents. Consequently, client code can implement more robust and cleaner retrieval logic by leveraging the Optional pattern.

      Example usage:

       
        // Given a collection
        DataApiCollection<Document> collection;
        // Assuming a Document in the collection with an id field
        Document doc = new Document().id(1).append("name", "John Doe");
        // To find the document with the id 1
        Optional<Document> foundDoc = collection.findOne(Filters.eq("_id", 1));
        foundDoc.ifPresent(System.out::println);
       
       
      Parameters:
      filter - The Filter instance encapsulating the search criteria used to pinpoint the desired document. This object specifies the exact conditions that must be met for a document to be selected as a match.
      Returns:
      An Optional encapsulating the found document, if any, that meets the filter criteria. If no document matches the specified conditions, an empty Optional is returned, ensuring that retrieval operations can be performed safely without the concern of NoSuchElementException.
    • findOne Link icon

      public Optional<T> findOne(Filter filter, CollectionFindOneOptions findOneOptions)
      Attempts to find a single document within the collection that matches the given filter criteria. This method is designed to return the first document that satisfies the filter conditions, making it particularly useful for retrieving specific documents when unique identifiers or specific criteria are known. If no document matches the filter, the method will return an empty Optional, indicating the absence of a matching document. This approach avoids throwing exceptions for non-existent documents, thereby facilitating cleaner and more robust error handling in client code.

      Example usage:

       
        // Given a collection
        DataApiCollection<Document> collection;
        // Assuming a Document in the collection with an id field
        Document doc = new Document().id(1).append("name", "John Doe");
        // To find the document with the id 1
        FindOneOptions options2 = FindOneOptions.builder()
          .withIncludeSimilarity()     // return similarity in vector search
          .projections("_id", "name")  // return a subset of fields
          .build();
        Optional<Document> foundDoc = collection.findOne(Filters.eq("_id", 1), );
        foundDoc.ifPresent(System.out::println);
       
       
      Parameters:
      filter - The Filter instance containing the criteria used to identify the desired document. It specifies the conditions that a document must meet to be considered a match.
      findOneOptions - The CollectionFindOneOptions instance containing additional options for the find operation,
      Returns:
      An Optional that contains the found document if one exists that matches the filter criteria. Returns an empty Optional if no matching document is found, enabling safe retrieval operations without the risk of NoSuchElementException.
    • findOne Link icon

      public Optional<T> findOne(CollectionFindOneOptions findOneOptions)
      Syntax sugar to provide a findOne command without a filter @see findOne(Filter, CollectionFindOneOptions).
      Parameters:
      findOneOptions - find one without a filter
      Returns:
      An Optional that contains the found document if one exists that matches the filter criteria. Returns an empty Optional if no matching document is found, enabling safe retrieval operations without the risk of NoSuchElementException.
    • findOneASync Link icon

      public CompletableFuture<Optional<T>> findOneASync(Filter filter)
      Initiates an asynchronous search to find a single document that matches the given filter criteria. This method leverages the functionality of to perform the search, but it does so asynchronously, returning a CompletableFuture. This approach allows the calling thread to remain responsive and perform other tasks while the search operation completes. The result of the operation is wrapped in a CompletableFuture that, upon completion, will contain an Optional instance. This instance either holds the document that matches the filter criteria or is empty if no such document exists.
      Parameters:
      filter - The Filter specifying the conditions that the document must meet to be considered a match. This parameter determines how the search is conducted and what criteria the document must satisfy to be retrieved.
      Returns:
      CompletableFuture that, when completed, will contain the result of the search operation. If a matching document is found, the Optional is non-empty; otherwise, it is empty to indicate the absence of a matching document. This future allows for non-blocking operations and facilitates the integration of asynchronous programming patterns.
    • findOneASync Link icon

      public CompletableFuture<Optional<T>> findOneASync(Filter filter, CollectionFindOneOptions findOneOptions)
      Asynchronously attempts to find a single document within the collection that matches the given filter criteria, utilizing the specified CollectionFindOneOptions for the query. This method offers a non-blocking approach to querying the database, making it well-suited for applications requiring efficient I/O operations without compromising the responsiveness of the application.

      By executing the search operation in an asynchronous manner, this method allows other tasks to proceed concurrently, effectively utilizing system resources and improving application throughput. The query leverages a Filter instance to define the search criteria, and CollectionFindOneOptions to specify query customizations, such as projection or sort parameters.

      In cases where no document matches the filter, the method returns a CompletableFuture completed with an empty Optional, thus avoiding exceptions for non-existent documents. This behavior ensures a more graceful handling of such scenarios, allowing for cleaner and more robust client code by leveraging the Optional pattern within asynchronous workflows.

      Parameters:
      filter - The Filter instance encapsulating the criteria used to identify the desired document. It defines the conditions that a document must meet to be considered a match.
      findOneOptions - The CollectionFindOneOptions providing additional query configurations such as projection and sort criteria to tailor the search operation.
      Returns:
      A CompletableFuture that, upon completion, contains an Optional with the found document if one exists matching the filter criteria. If no matching document is found, a completed future with an empty Optional is returned, facilitating safe asynchronous retrieval.

      Example usage:

       
       Filter filter = Filters.eq("id", 1);
       FindOneOptions options = FindOneOptions.builder().projection("name");
       CompletableFuture<Optional<Document>> futureDoc = collection.findOneASync(filter, options);
       futureDoc.thenAccept(doc -> doc.ifPresent(System.out::println));
       
       
    • findAll Link icon

      public FindIterable<T> findAll()
      Retrieves all documents in the collection.

      This method returns an iterable interface that allows iterating over all documents in the collection, without applying any filters. It leverages the default CollectionFindOptions for query execution.

      Returns:
      A FindIterable for iterating over all documents in the collection.
    • findAllWithCursor Link icon

      public CollectionCursor<T> findAllWithCursor()
      Retrieves all documents in the collection.

      This method returns an iterable interface that allows iterating over all documents in the collection, without applying any filters. It leverages the default CollectionFindOptions for query execution.

      Returns:
      A CollectionCursor for iterating over all documents in the collection.
    • findById Link icon

      public Optional<T> findById(Object id)
      Retrieves a document by its identifier from the collection.

      This method searches for a document with the specified id. If a matching document is found, it is returned wrapped in an Optional, otherwise, an empty Optional is returned. This approach provides a null-safe way to handle the presence or absence of a document.

      Parameters:
      id - The identifier of the document to find.
      Returns:
      An Optional containing the found document, or an empty Optional if no document matches the provided id.
    • find Link icon

      public FindIterable<T> find(Filter filter)
      Finds all documents in the collection.
      Parameters:
      filter - the query filter
      Returns:
      the find iterable interface
    • find Link icon

      public FindIterable<T> find(Filter filter, CollectionFindOptions options)
      Finds all documents in the collection.
      Parameters:
      filter - the query filter
      options - options of find one
      Returns:
      the find iterable interface
    • find Link icon

      public FindIterable<T> find(CollectionFindOptions options)
      Finds all documents in the collection.
      Parameters:
      options - options of find one
      Returns:
      the find iterable interface
    • findPage Link icon

      public Page<T> findPage(Filter filter, CollectionFindOptions options)
      Executes a paginated 'find' query on the collection using the specified filter and find options.

      This method constructs and executes a command to fetch a specific page of documents from the collection that match the provided filter criteria. It allows for detailed control over the query through FindOptions, such as sorting, projection, pagination, and more. The result is wrapped in a Page object, which includes the documents found, the page size, and the state for fetching subsequent pages.

      Pagination is facilitated by the skip, limit, and pageState parameters within FindOptions, enabling efficient data retrieval in scenarios where the total dataset is too large to be fetched in a single request. Optionally, similarity scoring can be included if includeSimilarity is set, which is useful for vector-based search queries.

      The method processes the command's response, mapping each document to the specified document class and collecting them into a list. This list, along with the maximum page size and the next page state, is used to construct the Page object returned by the method.

      Parameters:
      filter - The filter criteria used to select documents from the collection.
      options - The CollectionFindOptions providing additional query parameters, such as sorting and pagination.
      Returns:
      A Page object containing the documents that match the query, along with pagination information.
    • findPageASync Link icon

      public CompletableFuture<Page<T>> findPageASync(Filter filter, CollectionFindOptions options)
      Executes a paginated 'find' query on the collection using the specified filter and find options asynchronously.

      This method constructs and executes a command to fetch a specific page of documents from the collection that match the provided filter criteria. It allows for detailed control over the query through FindOptions, such as sorting, projection, pagination, and more. The result is wrapped in a Page object, which includes the documents found, the page size, and the state for fetching subsequent pages.

      Pagination is facilitated by the skip, limit, and pageState parameters within FindOptions, enabling efficient data retrieval in scenarios where the total dataset is too large to be fetched in a single request. Optionally, similarity scoring can be included if includeSimilarity is set, which is useful for vector-based search queries.

      The method processes the command's response, mapping each document to the specified document class and collecting them into a list. This list, along with the maximum page size and the next page state, is used to construct the Page object returned by the method.

      Parameters:
      filter - The filter criteria used to select documents from the collection.
      options - The CollectionFindOptions providing additional query parameters, such as sorting and pagination.
      Returns:
      A Page object containing the documents that match the query, along with pagination information.
    • distinct Link icon

      public <F> CollectionDistinctIterable<T,F> distinct(String fieldName, Class<F> resultClass)
      Gets the distinct values of the specified field name. The iteration is performed at CLIENT-SIDE and will exhaust all the collections elements.
      Type Parameters:
      F - the target type of the iterable.
      Parameters:
      fieldName - the field name
      resultClass - the class to cast any distinct items into.
      Returns:
      an iterable of distinct values
    • distinct Link icon

      public <F> CollectionDistinctIterable<T,F> distinct(String fieldName, Filter filter, Class<F> resultClass)
      Gets the distinct values of the specified field name.
      Type Parameters:
      F - the target type of the iterable.
      Parameters:
      fieldName - the field name
      filter - the query filter
      resultClass - the class to cast any distinct items into.
      Returns:
      an iterable of distinct values
    • countDocuments Link icon

      public int countDocuments(int upperBound) throws TooManyDocumentsToCountException
      Counts the number of documents in the collection.

      Takes in a `upperBound` option which dictates the maximum number of documents that may be present before a TooManyDocumentsToCountException is thrown. If the limit is higher than the highest limit accepted by the Data API, a TooManyDocumentsToCountException will be thrown anyway (i.e. `1000`).

      Count operations are expensive: for this reason, the best practice is to provide a reasonable `upperBound` according to the caller expectations. Moreover, indiscriminate usage of count operations for sizeable amounts of documents (i.e. in the thousands and more) is discouraged in favor of alternative application-specific solutions. Keep in mind that the Data API has a hard upper limit on the amount of documents it will count, and that an exception will be thrown by this method if this limit is encountered.

      Parameters:
      upperBound - The maximum number of documents to count.
      Returns:
      The number of documents in the collection.
      Throws:
      TooManyDocumentsToCountException - If the number of documents counted exceeds the provided limit.
    • estimatedDocumentCount Link icon

      public long estimatedDocumentCount()
      Calling an estimatedDocumentCount with default options. @see estimatedDocumentCount(EstimatedCountDocumentsOptions)
      Returns:
      the estimated number of documents in the collection.
    • estimatedDocumentCount Link icon

      public long estimatedDocumentCount(EstimatedCountDocumentsOptions options)
      Executes the "estimatedDocumentCount" command to estimate the number of documents in a collection.

      This method sends a command to estimate the document count and parses the count from the command's response. It handles the execution of the command and the extraction of the document count from the response.

      Parameters:
      options - the options to apply to the operation
      Returns:
      the estimated number of documents in the collection.
    • countDocuments Link icon

      public int countDocuments(Filter filter, int upperBound, CountDocumentsOptions options) throws TooManyDocumentsToCountException
      Counts the number of documents in the collection with a filter.

      Takes in a `upperBound` option which dictates the maximum number of documents that may be present before a TooManyDocumentsToCountException is thrown. If the limit is higher than the highest limit accepted by the Data API, a TooManyDocumentsToCountException will be thrown anyway (i.e. `1000`).

      Count operations are expensive: for this reason, the best practice is to provide a reasonable `upperBound` according to the caller expectations. Moreover, indiscriminate usage of count operations for sizeable amounts of documents (i.e. in the thousands and more) is discouraged in favor of alternative application-specific solutions. Keep in mind that the Data API has a hard upper limit on the amount of documents it will count, and that an exception will be thrown by this method if this limit is encountered.

      Parameters:
      filter - A filter to select the documents to count. If not provided, all documents will be counted.
      upperBound - The maximum number of documents to count.
      options - overriding options for the count operation.
      Returns:
      The number of documents in the collection.
      Throws:
      TooManyDocumentsToCountException - If the number of documents counted exceeds the provided limit.
    • countDocuments Link icon

      public int countDocuments(Filter filter, int upperBound) throws TooManyDocumentsToCountException
      Implementation of the @see countDocuments(Filter, int, CountDocumentsOptions) method with default options.
      Parameters:
      filter - filter to count
      upperBound - The maximum number of documents to count. It must be lower than the maximum limit accepted by the Data API.
      Returns:
      The number of documents in the collection.
      Throws:
      TooManyDocumentsToCountException - If the number of documents counted exceeds the provided limit.
    • deleteOne Link icon

      public CollectionDeleteResult deleteOne(Filter filter)
      Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not modified.
      Parameters:
      filter - the query filter to apply the delete operation
      Returns:
      the result of the remove one operation
    • deleteOne Link icon

      public CollectionDeleteResult deleteOne(Filter filter, CollectionDeleteOneOptions collectionDeleteOneOptions)
      Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not modified.
      Parameters:
      filter - the query filter to apply the delete operation
      collectionDeleteOneOptions - the option to driver the deletes (here sort)
      Returns:
      the result of the remove one operation
    • deleteMany Link icon

      public CollectionDeleteResult deleteMany(Filter filter, CollectionDeleteManyOptions options)
      Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
      Parameters:
      filter - the query filter to apply the delete operation
      options - the options to apply to the operation
      Returns:
      the result of the remove many operation
    • deleteMany Link icon

      public CollectionDeleteResult deleteMany(Filter filter)
      Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
      Parameters:
      filter - the query filter to apply the delete operation
      Returns:
      the result of the remove many operation
    • deleteAll Link icon

      public CollectionDeleteResult deleteAll()
      Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified.
      Returns:
      the result of the remove many operation
    • exists Link icon

      public boolean exists()
      Checks if the specified collection exists within the current namespace.

      This method delegates the existence check to the existCollection method of the associated namespace, evaluates the existence based on the collection's name, as retrieved by getName().

      Returns:
      true if the collection exists within the namespace, false otherwise.
    • drop Link icon

      public void drop()
      Delete the current collection and all documents that its contains.
    • findOneAndReplace Link icon

      public Optional<T> findOneAndReplace(Filter filter, T replacement)
      Atomically find a document and replace it.
      Parameters:
      filter - the query filter to apply the replace operation
      replacement - the replacement document
      Returns:
      the document that was replaced. Depending on the value of the returnOriginal property, this will either be the document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be returned
    • findOneAndReplace Link icon

      public Optional<T> findOneAndReplace(Filter filter, T replacement, CollectionFindOneAndReplaceOptions options)
      Atomically find a document and replace it.

      Note: Supports retryable writes on MongoDB server versions 3.6 or higher when the retryWrites setting is enabled.

      Parameters:
      filter - the query filter to apply the replace operation
      replacement - the replacement document
      options - the options to apply to the operation
      Returns:
      the document that was replaced. Depending on the value of the returnOriginal property, this will either be the document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be returned
    • replaceOne Link icon

      public CollectionUpdateResult replaceOne(Filter filter, T replacement)
      Replace a single document on the collection with a new one, optionally inserting a new document if no match is found.
      Parameters:
      filter - the query filter to apply the replace operation
      replacement - the replacement document
      Returns:
      result of the replace one operation
    • replaceOne Link icon

      public CollectionUpdateResult replaceOne(Filter filter, T replacement, CollectionReplaceOneOptions collectionReplaceOneOptions)
      Replace a document in the collection according to the specified arguments.
      Parameters:
      filter - the query filter to apply the replace operation
      replacement - the replacement document
      collectionReplaceOneOptions - the options to apply to the replace operation
      Returns:
      the result of the replace one operation
    • findOneAndUpdate Link icon

      public Optional<T> findOneAndUpdate(Filter filter, Update update)
      Atomically find a document and update it.

      Note: Supports retryable writes on MongoDB server versions 3.6 or higher when the retryWrites setting is enabled.

      Parameters:
      filter - a document describing the query filter, which may not be null.
      update - a document describing the update, which may not be null. The update to apply must include at least one update operator.
      Returns:
      the document that was updated before the update was applied. If no documents matched the query filter, then null will be returned
    • findOneAndUpdate Link icon

      public Optional<T> findOneAndUpdate(Filter filter, Update update, CollectionFindOneAndUpdateOptions options)
      Atomically find a document and update it.
      Parameters:
      filter - a document describing the query filter, which may not be null.
      update - a document describing the update, which may not be null. The update to apply must include at least one update operator.
      options - the options to apply to the operation
      Returns:
      the document that was updated. Depending on the value of the returnOriginal property, this will either be the document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be returned
    • updateOne Link icon

      public CollectionUpdateResult updateOne(Filter filter, Update update)
      Update a single document in the collection according to the specified arguments.
      Parameters:
      filter - a document describing the query filter, which may not be null.
      update - a document describing the update, which may not be null. The update to apply must include at least one update operator.
      Returns:
      the result of the update one operation
    • updateOne Link icon

      public CollectionUpdateResult updateOne(Filter filter, Update update, UpdateOneOptions updateOptions)
      Update a single document in the collection according to the specified arguments.
      Parameters:
      filter - a document describing the query filter, which may not be null.
      update - a document describing the update, which may not be null. The update to apply must include at least one update operator.
      updateOptions - the options to apply to the update operation
      Returns:
      the result of the update one operation
    • updateMany Link icon

      public CollectionUpdateResult updateMany(Filter filter, Update update)
      Update all documents in the collection according to the specified arguments.
      Parameters:
      filter - a document describing the query filter, which may not be null.
      update - a document describing the update, which may not be null. The update to apply must include only update operators.
      Returns:
      the result of the update many operation
    • updateMany Link icon

      public CollectionUpdateResult updateMany(Filter filter, Update update, CollectionUpdateManyOptions options)
      Update all documents in the collection according to the specified arguments.
      Parameters:
      filter - a document describing the query filter, which may not be null.
      update - a document describing the update, which may not be null. The update to apply must include only update operators.
      options - the options to apply to the update operation
      Returns:
      the result of the update many operation
    • findOneAndDelete Link icon

      public Optional<T> findOneAndDelete(Filter filter)
      Atomically find a document and remove it.
      Parameters:
      filter - the query filter to find the document with
      Returns:
      the document that was removed. If no documents matched the query filter, then null will be returned
    • findOneAndDeleteAsync Link icon

      public CompletableFuture<Optional<T>> findOneAndDeleteAsync(Filter filter)
      Delete and return a document asynchronous.
      Parameters:
      filter - filter to delete
      Returns:
      the document that was removed. If no documents matched the query filter, then null will be returned
    • findOneAndDelete Link icon

      public Optional<T> findOneAndDelete(Filter filter, CollectionFindOneAndDeleteOptions options)
      Atomically find a document and remove it.
      Parameters:
      filter - the query filter to find the document with
      options - the options to apply to the operation
      Returns:
      the document that was removed. If no documents matched the query filter, then null will be returned