Find and delete a document
Documents represent a single row or record of data in Astra DB Serverless databases.
You use the Collection
class to work with documents through the Data API clients.
For instructions to get a Collection
object, see Work with collections.
For general information about working with documents, including common operations and operators, see the Work with documents.
For more information about the Data API and clients, see Get started with the Data API.
Find and delete a document
Find one document that matches a filter condition, delete it, and then return the deleted document.
Sort and filter clauses can use only indexed fields. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries. |
-
Python
-
TypeScript
-
Java
-
curl
For more information, see the Client reference.
Find a document matching a filter condition, and then delete it:
deleted_document = collection.find_one_and_delete({"status": "stale_entry"})
Locate and delete the document most similar to a query vector from either $vector
or $vectorize
:
deleted_document = collection.find_one_and_delete(
{},
sort={"$vector": [0.1, 0.2, 0.3]},
)
Parameters:
Name | Type | Summary |
---|---|---|
|
|
A predicate expressed as a dictionary according to the Data API filter syntax.
For example: |
|
|
See Find a document and Projection clauses. |
|
|
See Find a document and Sort clause. |
|
|
A timeout, in milliseconds, for the underlying HTTP request. This method uses the collection-level timeout by default. |
Returns:
Dict[str, Any]
- The deleted document or, if no matches are found, None
.
The exact fields returned depend on the projection
parameter.
Example response
{'_id': 199, 'status': 'stale_entry', 'request_id': 'A4431'}
Example:
from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
database = client.get_database("API_ENDPOINT")
collection = database.my_collection
collection.insert_many(
[
{"species": "swan", "class": "Aves"},
{"species": "frog", "class": "Amphibia"},
],
)
collection.find_one_and_delete(
{"species": {"$ne": "frog"}},
projection={"species": True},
)
# prints: {'_id': '5997fb48-...', 'species': 'swan'}
collection.find_one_and_delete({"species": {"$ne": "frog"}})
# (returns None for no matches)
For more information, see the Client reference.
Find a document matching a filter condition, and then delete it:
const deletedDoc = await collection.findOneAndDelete({ status: 'stale_entry' });
Locate and delete the document most similar to a query vector from either $vector
or $vectorize
:
const deletedDoc = await collection.findOneAndDelete(
{},
{ sort: { $vector: [0.1, 0.2, 0.3] } },
);
Parameters:
Name | Type | Summary |
---|---|---|
|
A filter to select the document to delete. For a list of available operators, see Data API operators. For additional examples, see Find documents using filter clauses. |
|
|
The options for this operation. |
Options (FindOneAndDeleteOptions
):
Name | Type | Summary |
---|---|---|
See Find a document and Projection clauses. |
||
See Find a document and Sort clauses. |
||
|
The maximum time in milliseconds that the client should wait for the operation to complete each underlying HTTP request. |
|
|
When true, returns |
Returns:
Promise<WithId<Schema> | null>
- The deleted document, or, if no matches are found, null
.
The exact fields returned depend on the projection
parameter.
Example:
import { DataAPIClient } from '@datastax/astra-db-ts';
// Reference an untyped collection
const client = new DataAPIClient('TOKEN');
const db = client.db('ENDPOINT', { keyspace: 'KEYSPACE' });
const collection = db.collection('COLLECTION');
(async function () {
// Insert some document
await collection.insertMany([
{ species: 'swan', class: 'Aves' },
{ species: 'frog', class: 'Amphibia' },
]);
// { _id: '...', species: 'swan' }
await collection.findOneAndDelete(
{ species: { $ne: 'frog' } },
{ projection: { species: 1 } },
);
// null
await collection.findOneAndDelete(
{ species: { $ne: 'frog' } },
);
})();
Operations on documents are performed at the Collection
level.
Collection is a generic class with the default type of Document
.
You can specify your own type, and the object is serialized by Jackson.
For more information, see the Client reference.
Most methods have synchronous and asynchronous flavors, where the asynchronous version is suffixed by Async
and returns a CompletableFuture
:
// Synchronous
Optional<T> findOneAndDelete(Filter filter);
Optional<T> findOneAndDelete(Filter filter, FindOneAndDeleteOptions options);
// Asynchronous
CompletableFuture<Optional<T>> findOneAndDeleteAsync(Filter filter);
CompletableFuture<Optional<T>> findOneAndDeleteAsync(Filter filter, FindOneAndDeleteOptions options);
Parameters:
Name | Type | Summary |
---|---|---|
|
|
Filter criteria to find the document to delete.
The filter is a JSON object that can contain any valid Data API filter expression.
For a list of available operators, see Data API operators.
For examples and options, including |
|
Set the different options for the find and delete operation, including the following:
|
Returns:
DeleteResult
- Wrapper that contains the deleted count.
Example:
package com.datastax.astra.client.collection;
import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import java.util.Optional;
import static com.datastax.astra.client.model.Filters.lt;
public class FindOneAndDelete {
public static void main(String[] args) {
Collection<Document> collection = new DataAPIClient("TOKEN")
.getDatabase("API_ENDPOINT")
.getCollection("COLLECTION_NAME");
// Building a filter
Filter filter = Filters.and(
Filters.gt("field2", 10),
lt("field3", 20),
Filters.eq("field4", "value"));
// It will return the document before deleting it
Optional<Document> docBeforeRelease = collection.findOneAndDelete(filter);
}
}
Find a document matching a filter condition, and then delete it:
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOneAndDelete": {
"filter": {
"customer.name": "Fred Smith",
"_id": "13"
}
}
}' | jq
Locate and delete the document most similar to a query vector from either $vector
or $vectorize
:
"findOneAndDelete": {
"sort": { "$vector": [0.1, 0.2, 0.3] },
"projection": { "$vector": 1 }
}
Parameters:
Name | Type | Summary |
---|---|---|
|
|
The Data API command to find and delete the first document in a collection that matches the given |
|
|
Search criteria to find the document to delete.
For a list of available operators, see Data API operators.
For |
|
|
Select a subset of fields to include in the response for the returned document. If empty or unset, the default projection is used. The default projection doesn’t always include all document fields. For more information and examples, see Projection clauses. |
Returns:
A successful response incudes data
and status
objects:
-
The
data
object can contain the deleted document, based on theprojection
parameter, if a matching document was found and deleted. -
The
status
object contains the number of deleted documents. ForfindOneAndDelete
, this is either1
(one document deleted) or0
(no matches).
{
"status": {
"deletedCount": 1
}
}