Class Collection<T>
- Type Parameters:
T
- Java bean to unmarshall documents for collection.
- All Implemented Interfaces:
CommandRunner
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 Summary
Modifier and TypeFieldDescriptionprotected static final String
parameters names.protected static final String
parameters names.static final DataAPISerializer
Default collection serializer.protected static final String
parameters names.Fields inherited from class com.datastax.astra.internal.command.AbstractCommandRunner
apiEndpoint, ARG_CLAZZ, ARG_DATABASE, httpClient, INPUT_INCLUDE_SIMILARITY, INPUT_INCLUDE_SORT_VECTOR, INPUT_ORDERED, INPUT_PAGE_STATE, INPUT_RETURN_DOCUMENT, INPUT_RETURN_DOCUMENT_RESPONSES, INPUT_UPSERT, options, RESULT_COUNT, RESULT_DELETED_COUNT, RESULT_INSERTED_IDS, RESULT_MATCHED_COUNT, RESULT_MODIFIED_COUNT, RESULT_MORE_DATA, RESULT_UPSERTED_ID
-
Constructor Summary
ConstructorDescriptionCollection
(Database db, String collectionName, CollectionOptions collectionOptions, Class<T> documentClass) Constructs an instance of a collection within the specified database. -
Method Summary
Modifier and TypeMethodDescriptionint
countDocuments
(int upperBound) Counts the number of documents in the collection.int
countDocuments
(Filter filter, int upperBound) Implementation of the @seecountDocuments(Filter, int, CountDocumentsOptions)
method with default options.int
countDocuments
(Filter filter, int upperBound, CountDocumentsOptions options) Counts the number of documents in the collection with a filter.Removes all documents from the collection that match the given query filter.deleteMany
(Filter filter) Removes all documents from the collection that match the given query filter.deleteMany
(Filter filter, CollectionDeleteManyOptions options) Removes all documents from the collection that match the given query filter.Removes at most one document from the collection that matches the given filter.deleteOne
(Filter filter, CollectionDeleteOneOptions collectionDeleteOneOptions) Removes at most one document from the collection that matches the given filter.<F> CollectionDistinctIterable
<T, F> Gets the distinct values of the specified field name.<F> CollectionDistinctIterable
<T, F> Gets the distinct values of the specified field name.void
drop()
Delete the current collection and all documents that its contains.long
Calling an estimatedDocumentCount with default options.long
Executes the "estimatedDocumentCount" command to estimate the number of documents in a collection.boolean
exists()
Checks if the specified collection exists within the current namespace.find
(CollectionFindOptions options) Finds all documents in the collection.Finds all documents in the collection.find
(Filter filter, CollectionFindOptions options) Finds all documents in the collection.findAll()
Retrieves all documents in the collection.Retrieves all documents in the collection.Retrieves a document by its identifier from the collection.findOne
(CollectionFindOneOptions findOneOptions) Syntax sugar to provide a findOne command without a filter @seefindOne(Filter, CollectionFindOneOptions)
.Attempts to find a single document within the collection that matches the given filter criteria.findOne
(Filter filter, CollectionFindOneOptions findOneOptions) Attempts to find a single document within the collection that matches the given filter criteria.findOneAndDelete
(Filter filter) Atomically find a document and remove it.findOneAndDelete
(Filter filter, CollectionFindOneAndDeleteOptions options) Atomically find a document and remove it.findOneAndDeleteAsync
(Filter filter) Delete and return a document asynchronous.findOneAndReplace
(Filter filter, T replacement) Atomically find a document and replace it.findOneAndReplace
(Filter filter, T replacement, CollectionFindOneAndReplaceOptions options) Atomically find a document and replace it.findOneAndUpdate
(Filter filter, Update update) Atomically find a document and update it.findOneAndUpdate
(Filter filter, Update update, CollectionFindOneAndUpdateOptions options) Atomically find a document and update it.findOneASync
(Filter filter) Initiates an asynchronous search to find a single document that matches the given filter criteria.findOneASync
(Filter filter, CollectionFindOneOptions findOneOptions) Asynchronously attempts to find a single document within the collection that matches the given filter criteria, utilizing the specifiedCollectionFindOneOptions
for the query.findPage
(Filter filter, CollectionFindOptions options) Executes a paginated 'find' query on the collection using the specified filter and find options.findPageASync
(Filter filter, CollectionFindOptions options) Executes a paginated 'find' query on the collection using the specified filter and find options asynchronously.Retrieves the full definition of the collection, encompassing both its name and its configuration options.Retrieves the name of the parent keyspace associated with this collection.insertMany
(List<? extends T> documents) Inserts a batch of documents into the collection using default insertion options.insertMany
(List<? extends T> documents, CollectionInsertManyOptions options) Inserts a batch of documents into the collection concurrently, optimizing the insertion process for large datasets.insertMany
(T... documents) Inserts a batch of documents into the collection using default insertion options.insertManyAsync
(List<? extends T> documents) Asynchronously inserts a batch of documents into the collection using default insertion options.insertManyAsync
(List<? extends T> documents, CollectionInsertManyOptions options) Asynchronously inserts a batch of documents into the collection with customizable insertion options.Inserts a single document into the collection as an atomic operation, ensuring that the document is added in a single, indivisible step.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.insertOneAsync
(T document) Asynchronously inserts a single document into the collection.insertOneAsync
(T document, CollectionInsertOneOptions options) Asynchronous implementation ofinsertOne(Object, CollectionInsertOneOptions)
.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.replaceOne
(Filter filter, T replacement, CollectionReplaceOneOptions collectionReplaceOneOptions) Replace a document in the collection according to the specified arguments.updateMany
(Filter filter, Update update) Update all documents in the collection according to the specified arguments.updateMany
(Filter filter, Update update, CollectionUpdateManyOptions options) Update all documents in the collection according to the specified arguments.Update a single document in the collection according to the specified arguments.updateOne
(Filter filter, Update update, UpdateOneOptions updateOptions) Update a single document in the collection according to the specified arguments.Methods inherited from class com.datastax.astra.internal.command.AbstractCommandRunner
assertIsAstra, getApiEndpoint, getOptions, getSerializer, runCommand, runCommand, unmarshall
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface com.datastax.astra.client.core.commands.CommandRunner
runCommand, runCommand
-
Field Details
-
Constructor Details
-
Collection
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
- TheDatabase
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
- AString
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 collectiondocumentClass
- TheClass
object representing the schema of documents storedExample 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
-
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
Retrieves the full definition of the collection, encompassing both its name and its configuration options. This comprehensive information is encapsulated in aCollectionInfo
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
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 touuid
, ids will be uuid v4UUID
- If
defaultId
is set toobjectId
, ids will be anObjectId
- If
defaultId
is set touuidv6
, ids will be anUUIDv6
- If
defaultId
is set touuidv7
, ids will be anUUIDv7
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");
- If
-
insertOne
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 touuid
, ids will be uuid v4UUID
- If
defaultId
is set toobjectId
, ids will be anObjectId
- If
defaultId
is set touuidv6
, ids will be anUUIDv6
- If
defaultId
is set touuidv7
, ids will be anUUIDv7
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");
- If
-
insertOneAsync
Asynchronously inserts a single document into the collection. This method provides the same functionality asinsertOne(Object)
, but it operates asynchronously, returning aCompletableFuture
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 ininsertOne(Object)
.- Returns:
- A
CompletableFuture
that, upon completion, contains the result of the insert operation as anCollectionInsertOneResult
. 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
public final CompletableFuture<CollectionInsertOneResult> insertOneAsync(T document, CollectionInsertOneOptions options) Asynchronous implementation ofinsertOne(Object, CollectionInsertOneOptions)
.- Parameters:
document
- document to insertoptions
- 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
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 anIllegalArgumentException
, 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 singleCollectionInsertManyResult
.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 singleCollectionInsertManyResult
.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
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 toinsertMany(List, CollectionInsertManyOptions)
, allowing for non-blocking operations. It employs default or specifiedCollectionInsertManyOptions
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 providedoptions
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 theCollectionInsertManyResult
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
Inserts a batch of documents into the collection using default insertion options. This method is a simplified version ofinsertMany(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 overloadedinsertMany(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
Inserts a batch of documents into the collection using default insertion options. This method is a simplified version ofinsertMany(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 overloadedinsertMany(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
Asynchronously inserts a batch of documents into the collection using default insertion options. This method provides an asynchronous alternative toinsertMany(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 theCollectionInsertManyResult
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
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 theOptional
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
- TheFilter
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 emptyOptional
is returned, ensuring that retrieval operations can be performed safely without the concern ofNoSuchElementException
.
-
findOne
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 emptyOptional
, 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
- TheFilter
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
- TheCollectionFindOneOptions
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 emptyOptional
if no matching document is found, enabling safe retrieval operations without the risk ofNoSuchElementException
.
-
findOne
Syntax sugar to provide a findOne command without a filter @seefindOne(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 emptyOptional
if no matching document is found, enabling safe retrieval operations without the risk ofNoSuchElementException
.
-
findOneASync
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 aCompletableFuture
. 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 aCompletableFuture
that, upon completion, will contain anOptional
instance. This instance either holds the document that matches the filter criteria or is empty if no such document exists.- Parameters:
filter
- TheFilter
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
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 specifiedCollectionFindOneOptions
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, andCollectionFindOneOptions
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 emptyOptional
, 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 theOptional
pattern within asynchronous workflows.- Parameters:
filter
- TheFilter
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
- TheCollectionFindOneOptions
providing additional query configurations such as projection and sort criteria to tailor the search operation.- Returns:
- A
CompletableFuture
that, upon completion, contains anOptional
with the found document if one exists matching the filter criteria. If no matching document is found, a completed future with an emptyOptional
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
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
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
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 anOptional
, otherwise, an emptyOptional
is returned. This approach provides a null-safe way to handle the presence or absence of a document. -
find
Finds all documents in the collection.- Parameters:
filter
- the query filter- Returns:
- the find iterable interface
-
find
Finds all documents in the collection.- Parameters:
filter
- the query filteroptions
- options of find one- Returns:
- the find iterable interface
-
find
Finds all documents in the collection.- Parameters:
options
- options of find one- Returns:
- the find iterable interface
-
findPage
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 aPage
object, which includes the documents found, the page size, and the state for fetching subsequent pages.Pagination is facilitated by the
skip
,limit
, andpageState
parameters withinFindOptions
, 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 ifincludeSimilarity
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
- TheCollectionFindOptions
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
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 aPage
object, which includes the documents found, the page size, and the state for fetching subsequent pages.Pagination is facilitated by the
skip
,limit
, andpageState
parameters withinFindOptions
, 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 ifincludeSimilarity
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
- TheCollectionFindOptions
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
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 nameresultClass
- the class to cast any distinct items into.- Returns:
- an iterable of distinct values
-
distinct
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 namefilter
- the query filterresultClass
- the class to cast any distinct items into.- Returns:
- an iterable of distinct values
-
countDocuments
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, aTooManyDocumentsToCountException
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
public long estimatedDocumentCount()Calling an estimatedDocumentCount with default options. @seeestimatedDocumentCount(EstimatedCountDocumentsOptions)
- Returns:
- the estimated number of documents in the collection.
-
estimatedDocumentCount
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
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, aTooManyDocumentsToCountException
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
Implementation of the @seecountDocuments(Filter, int, CountDocumentsOptions)
method with default options.- Parameters:
filter
- filter to countupperBound
- 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
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
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 operationcollectionDeleteOneOptions
- the option to driver the deletes (here sort)- Returns:
- the result of the remove one operation
-
deleteMany
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 operationoptions
- the options to apply to the operation- Returns:
- the result of the remove many operation
-
deleteMany
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
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
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
public void drop()Delete the current collection and all documents that its contains. -
findOneAndReplace
Atomically find a document and replace it.- Parameters:
filter
- the query filter to apply the replace operationreplacement
- 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
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 operationreplacement
- the replacement documentoptions
- 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
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 operationreplacement
- the replacement document- Returns:
- result of the replace one operation
-
replaceOne
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 operationreplacement
- the replacement documentcollectionReplaceOneOptions
- the options to apply to the replace operation- Returns:
- the result of the replace one operation
-
findOneAndUpdate
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
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
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
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
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
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
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
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
Atomically find a document and remove it.- Parameters:
filter
- the query filter to find the document withoptions
- 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
-