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

filter

Optional[Dict[str, Any]]

A predicate expressed as a dictionary according to the Data API filter syntax. For example: {}, {"name": "John"}, {"price": {"$lt": 100}}, {"$and": [{"name": "John"}, {"price": {"$lt": 100}}]}. For a list of available operators, see Data API operators. For additional examples, see Find documents using filter clauses.

projection

Optional[Union[Iterable[str], Dict[str, bool]]]

See Find a document and Projection clauses.

sort

Optional[Dict[str, Any]]

See Find a document and Sort clause.

max_time_ms

Optional[int]

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

filter

Filter<Schema>

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.

options?

FindOneAndDeleteOptions

The options for this operation.

Name Type Summary

projection?

Projection

See Find a document and Projection clauses.

sort?

Sort

See Find a document and Sort clauses.

maxTimeMS?

number

The maximum time in milliseconds that the client should wait for the operation to complete each underlying HTTP request.

includeResultMetadata?

boolean

When true, returns ok: 1, in addition to the document, if the command executed successfully.

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 (optional)

Filter

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 projection and sort, see Find documents using filter clauses.

options (optional)

FindOneAndDeleteOptions

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

findOneAndDelete

command

The Data API command to find and delete the first document in a collection that matches the given filter/sort criteria. If there is no match, then no action is taken.

sort, filter

object

Search criteria to find the document to delete. For a list of available operators, see Data API operators. For sort and filter examples, see Find a document and Sort clauses.

projection

object

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 the projection parameter, if a matching document was found and deleted.

  • The status object contains the number of deleted documents. For findOneAndDelete, this is either 1 (one document deleted) or 0 (no matches).

{
  "status": {
    "deletedCount": 1
  }
}

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com