Delete documents reference

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. For instructions to get a Collection object, see the Collections reference.

For general information about working with documents, including common operations and operators, see the Documents reference.

Find and delete a document

Find one document that matches a filter condition, delete it, and then return the deleted document.

Sort and filter operations 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 filtering options.

projection

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

See Find a document and Projection operations.

sort

Optional[Dict[str, Any]]

See Find a document and Sort operations.

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 filtering options.

options?

FindOneAndDeleteOptions

The options for this operation.

Name Type Summary

projection?

Projection

See Find a document and Projection operations.

sort?

Sort

See Find a document and Sort operations.

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 filtering options.

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 --location -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 examples and parameters, see Find a document and Sort operations.

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 operations.

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
  }
}

Delete a document

Locate and delete one document in a collection.

deleteOne is similar to findOneAndDelete, except that the response includes only the result of the operation. The response doesn’t include a document object, and the request doesn’t support response-related parameters, such as projection or returnDocument.

Sort and filter operations 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:

# Find by ID
response = collection.delete_one({ "_id": "1" })

# Find by a document property
document = collection.delete_one({"location": "warehouse_C"})

# Find with a filter operator
document = collection.delete_one({"tag": {"$exists": True}})

Locate and delete the document most similar to a query vector from either $vector or $vectorize:

# Find by vector search with $vector
result = collection.delete_one({}, sort={"$vector": [.12, .52, .32]})

# Find by vector search with $vectorize
result = collection.delete_one({}, sort={"$vectorize": "Text to vectorize"})

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 filtering options.

sort

Optional[Dict[str, Any]]

See Find a document and Sort operations.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the underlying HTTP request. This method uses the collection-level timeout by default.

Returns:

DeleteResult - An object representing the response from the database after the delete operation. It includes information about the success of the operation.

Example response
DeleteResult(deleted_count=1, raw_results=...)

Example:

from astrapy import DataAPIClient
import astrapy
client = DataAPIClient("TOKEN")
database = client.get_database("API_ENDPOINT")
collection = database.my_collection

collection.insert_many([{"seq": 1}, {"seq": 0}, {"seq": 2}])

collection.delete_one({"seq": 1})
# prints: DeleteResult(deleted_count=1, raw_results=...)
collection.distinct("seq")
# prints: [0, 2]
collection.delete_one(
    {"seq": {"$exists": True}},
    sort={"seq": astrapy.constants.SortDocuments.DESCENDING},
)
# prints: DeleteResult(deleted_count=1, raw_results=...)
collection.distinct("seq")
# prints: [0]
collection.delete_one({"seq": 2})
# prints: DeleteResult(deleted_count=0, raw_results=...)

For more information, see the Client reference.

Find a document matching a filter condition, and then delete it:

// Find by ID
const result = await collection.deleteOne({ _id: '1' });

// Find by a document property
const result = await collection.deleteOne({ location: 'warehouse_C' });

// Find with a filter operator
const result = await collection.deleteOne({ tag: { $exists: true } });

Locate and delete the document most similar to a query vector from either $vector or $vectorize:

// Find by vector search with $vector
const result = await collection.deleteOne({}, { sort: { $vector: [.12, .52, .32] } });

// Find by vector search with $vectorize
const result = await collection.deleteOne({}, { sort: { $vectorize: 'Text to vectorize' } });

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 filtering options.

options?

DeleteOneOptions

The options for this operation.

Options (DeleteOneOptions):

Name Type Summary

sort?

Sort

See Find a document and Sort operations.

maxTimeMS?

number

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

Returns:

Promise<DeleteOneResult> - The result of the deletion operation.

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([{ seq: 1 }, { seq: 0 }, { seq: 2 }]);

  // { deletedCount: 1 }
  await collection.deleteOne({ seq: 1 });

  // [0, 2]
  await collection.distinct('seq');

  // { deletedCount: 1 }
  await collection.deleteOne({ seq: { $exists: true } }, { sort: { seq: -1 } });

  // [0]
  await collection.distinct('seq');

  // { deletedCount: 0 }
  await collection.deleteOne({ seq: 2 });
})();

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
DeleteResult deleteOne(Filter filter);
DeleteResult deleteOne(Filter filter, DeleteOneOptions options);

// Asynchronous
CompletableFuture<DeleteResult> deleteOneAsync(Filter filter);
CompletableFuture<DeleteResult> deleteOneAsync(Filter filter, DeleteOneOptions 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 filtering options.

options (optional)

DeleteOneOptions

Set the different options for the deleteOne() operation, including sort.

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.DeleteOneOptions;
import com.datastax.astra.client.model.DeleteResult;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.Sorts;

import static com.datastax.astra.client.model.Filters.lt;

public class DeleteOne {
    public static void main(String[] args) {
        Collection<Document> collection = new DataAPIClient("TOKEN")
                .getDatabase("API_ENDPOINT")
                .getCollection("COLLECTION_NAME");

        // Sample Filter
        Filter filter = Filters.and(
                Filters.gt("field2", 10),
                lt("field3", 20),
                Filters.eq("field4", "value"));

        // Delete one options
        DeleteOneOptions options = new DeleteOneOptions()
                .sort(Sorts.ascending("field2"));
        DeleteResult result = collection.deleteOne(filter, options);
        System.out.println("Deleted Count:" + result.getDeletedCount());
    }
}

Find a document matching a filter condition, and then delete it:

curl -sS --location -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 '{
  "deleteOne": {
    "filter": {
      "tags": "first"
    }
  }
}' | jq

Locate and update the document most similar to a query vector from either $vector or $vectorize:

"deleteOne": {
  "sort": { "$vector": [0.1, 0.2, 0.3] }
}

Parameters:

Name Type Summary

deleteOne

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 examples and parameters, see Find a document and Sort operations.

Returns:

A successful response returns the number of deleted documents. For deleteOne, this is either 1 (one document deleted) or 0 (no matches).

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

Delete documents

Delete all documents in a collection that match a given filter condition. If you supply an empty filter, then the operation deletes every document in the collection.

This operation doesn’t support sort conditions.

Sort and filter operations 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 documents in a collection that match a given filter, and then delete them:

delete_result = collection.delete_many({"status": "processed"})

An empty filter deletes all documents and completely empties the collection:

delete_result = collection.delete_many({})

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 filtering options.

An empty filter deletes all documents, completely emptying the collection.

max_time_ms

Optional[int]

The timeout, in milliseconds, for the entire delete operation. This method uses the collection-level timeout by default.

Returns:

DeleteResult - An object representing the response from the database after the delete operation. It includes information about the success of the operation. A response of deleted_count=-1 indicates that every document in the collection was deleted.

Example response
DeleteResult(deleted_count=2, raw_results=...)

The time required for the delete operation depends on the number of documents that match the filter.

To delete a large number of documents, this operation issues multiple sequential HTTP requests until all matching documents are deleted. You might need to increase the timeout parameter to allow enough time for all underlying HTTP requests.

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
database = client.get_database("A*PI_ENDPOINT")
collection = database.my_collection

collection.insert_many([{"seq": 1}, {"seq": 0}, {"seq": 2}])

collection.delete_many({"seq": {"$lte": 1}})
# prints: DeleteResult(raw_results=..., deleted_count=2)
collection.distinct("seq")
# prints: [2]
collection.delete_many({"seq": {"$lte": 1}})
# prints: DeleteResult(raw_results=..., deleted_count=0)

# An empty filter deletes all documents and completely empties the collection:
collection.delete_many({})
# prints: DeleteResult(raw_results=..., deleted_count=-1)

For more information, see the Client reference.

Find documents in a collection that match a given filter, and then delete them:

const result = await collection.deleteMany({ status: 'processed' });

An empty filter deletes all documents and completely empties the collection:

const result = await collection.deleteMany({});

Parameters:

Name Type Summary

filter

Filter<Schema>

A filter to select the documents to delete. For a list of available operators, see Data API operators. For additional examples, see Find documents using filtering options.

An empty filter deletes all documents, completely emptying the collection.

options?

WithTimeout

The timeout, in milliseconds, for the entire delete operation.

Returns:

Promise<DeleteManyResult> - The result of the deletion operation. A deleted count of -1 indicates that every document in the collection was deleted.

The time required for the delete operation depends on the number of documents that match the filter.

To delete a large number of documents, this operation issues multiple sequential HTTP requests until all matching documents are deleted. You might need to increase the timeout parameter to allow enough time for all underlying HTTP requests.

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([{ seq: 1 }, { seq: 0 }, { seq: 2 }]);

  // { deletedCount: 1 }
  await collection.deleteMany({ seq: { $lte: 1 } });

  // [2]
  await collection.distinct('seq');

  // { deletedCount: 0 }
  await collection.deleteMany({ seq: { $lte: 1 } });

  // { deletedCount: -1 }
  await collection.deleteMany({});
})();

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
DeleteResult deleteMany(Filter filter);

// Asynchronous
CompletableFuture<DeleteResult> deleteManyAsync(Filter filter);

An empty filter deletes all documents and completely empties the collection:

DeleteResult deleteMany();

Parameters:

Name Type Summary

filter (optional)

Filter

Filter criteria to find the documents 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 additional examples, see Find documents using filtering options.

An empty filter deletes all documents, completely emptying the collection.

Returns:

DeleteResult - Wrapper that contains the deleted count.

The time required for the delete operation depends on the number of documents that match the filter. To delete a large number of documents, this operation iterates over batches of documents until all matching documents are deleted.

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.DeleteResult;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;

import static com.datastax.astra.client.model.Filters.lt;

public class DeleteMany {
    public static void main(String[] args) {
        Collection<Document> collection = new DataAPIClient("TOKEN")
                .getDatabase("API_ENDPOINT")
                .getCollection("COLLECTION_NAME");

        // Sample Filter
        Filter filter = Filters.and(
                Filters.gt("field2", 10),
                lt("field3", 20),
                Filters.eq("field4", "value"));
        DeleteResult result = collection.deleteMany(filter);
        System.out.println("Deleted Count:" + result.getDeletedCount());

    }
}

Find documents in a collection that match a filter condition, and then delete them:

curl -sS --location -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 '{
  "deleteMany": {
    "filter": {
      "status": "inactive"
    }
  }
}' | jq

An empty filter or deleteMany object deletes all documents and completely empties the collection:

# Empty filter object
"deleteMany": { "filter": {} }

# Empty deleteMany object
"deleteMany": {}

Parameters:

Name Type Summary

deleteMany

command

The Data API command to delete all matching documents from a collection based on the provided filter criteria.

filter

object

A filter to select the documents to delete. For a list of available operators, see Data API operators. For additional examples, see Find documents using filtering options.

An empty filter deletes all documents, completely emptying the collection.

Returns:

A successful response returns the result of the delete operation. This operation deletes up to 20 documents at a time. If the deletedCount is 20, there might be more matching documents to delete.

{
  "status": {
    "deletedCount": 20
  }
}

To delete another batch of documents, reissue the same request. Continue issuing the deleteMany request until the deletedCount is less than 20.

Example of batch deletion

For this example, assume that you send the following deleteMany command and the server finds 30 matching documents:

{
    "deleteMany": {
        "filter": { "a": true }
    }
}

The server deletes the first 20 documents and then returns the following response:

{
  "status": {
    "moreData": true,
    "deletedCount": 20
  }
}

The server doesn’t tell you explicitly how many matches were found. However, the deletedCount of 20 indicates there could be more matching documents to delete. To delete the next batch of documents, reissue the same deleteMany command:

{
    "deleteMany": {
        "filter": { "a": true }
    }
}

This time, the server returns the following:

{
  "status": {
    "deletedCount": 10
  }
}

Because the deletedCount is less than 20, this indicates that all matching documents were deleted.

To confirm, you can reissue the deleteMany request and get a deletedCount of 0:

{
  "status": {
    "deletedCount": 0
  }
}

A deleted count of -1 indicates that every document in the collection was deleted. This occurs if you pass an empty filter or deleteMany object. In this case, you don’t need to delete documents in batches. With an empty filter, the server automatically iterates over batches of documents until all documents are deleted.

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

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 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