Update documents

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.

Update multiple documents

Use updateMany to find and update multiple documents at once.

This command is a combination of find and updateOne. However, updateMany doesn’t support sort clauses.

Like updateOne, the updateMany 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 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 documents matching a filter condition, and then edit a property in those documents:

results = collection.update_many(
    {"name": {"$exists": False}},
    {"$set": {"name": "unknown"}},
)

Locate and update multiple documents or insert a new one if no match is found:

results = collection.update_many(
    {"name": {"$exists": False}},
    {"$set": {"name": "unknown"}},
    upsert=True,
)

For more examples, see [update-one].

Parameters:

Name Type Summary

filter

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.

update

Dict[str, Any]

The update prescription to apply to the documents, expressed as a dictionary as per Data API syntax. For example: {"$set": {"field": "value"}}, {"$inc": {"counter": 10}} and {"$unset": {"field": ""}}. For examples and a list of available operators, see [find-and-update-a-document] and Data API operators.

upsert

bool

This parameter controls the behavior if there are no matches. If true and there are no matches, then the operation inserts one new document by applying the update to an empty document. If false and there are no matches, then the operation silently does nothing.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the operation. This method uses the collection-level timeout by default. You may need to increase the timeout duration when updating a large number of documents because the update requires multiple sequential HTTP requests.

Returns:

UpdateResult - An object representing the response from the database after the update operation. It includes information about the operation.

Example response
UpdateResult(update_info={'n': 2, 'updatedExisting': True, 'ok': 1.0, 'nModified': 2}, raw_results=...)

Example:

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

collection.insert_many([{"c": "red"}, {"c": "green"}, {"c": "blue"}])

collection.update_many({"c": {"$ne": "green"}}, {"$set": {"nongreen": True}})
# prints: UpdateResult(update_info={'n': 2, 'updatedExisting': True, 'ok': 1.0, 'nModified': 2}, raw_results=...)
collection.update_many({"c": "orange"}, {"$set": {"is_also_fruit": True}})
# prints: UpdateResult(update_info={'n': 0, 'updatedExisting': False, 'ok': 1.0, 'nModified': 0}, raw_results=...)
collection.update_many(
    {"c": "orange"},
    {"$set": {"is_also_fruit": True}},
    upsert=True,
)
# prints: UpdateResult(update_info={'n': 1, 'updatedExisting': False, 'ok': 1.0, 'nModified': 0, 'upserted': '46643050-...'}, raw_results=...)

For more information, see the Client reference.

Find documents matching a filter condition, and then edit a property in those documents:

const result = await collection.updateMany(
  { name: { $exists: false } },
  { $set: { title: 'unknown' } },
);

Locate and update multiple documents in a collection or insert a new one if no matches are found:

const result = await collection.updateMany(
  { name: { $exists: false } },
  { $set: { title: 'unknown' } },
  { upsert: true },
);

For more examples, see [update-one].

Parameters:

Name Type Summary

filter

Filter<Schema>

A filter to select the documents to update. For a list of available operators, see Data API operators. For additional examples, seeFind documents using filter clauses.

update

UpdateFilter<Schema>

The update to apply to the selected documents. For examples and a list of available operators, see [find-and-update-a-document] and Data API operators.

options?

UpdateManyOptions

The options for this operation.

Options (UpdateManyOptions):

Name Type Summary

upsert?

boolean

This parameter controls the behavior if there are no matches. If true and there are no matches, then the operation inserts one new document by applying the update to an empty document. If false and there are no matches, then the operation silently does nothing.

maxTimeMS?

number

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

Returns:

Promise<UpdateManyResult<Schema>> - The result of the update 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 documents
  await collection.insertMany([{ c: 'red' }, { c: 'green' }, { c: 'blue' }]);

  // { modifiedCount: 2, matchedCount: 2, upsertedCount: 0 }
  await collection.updateMany({ c: { $ne: 'green' } }, { $set: { nongreen: true } });

  // { modifiedCount: 0, matchedCount: 0, upsertedCount: 0 }
  await collection.updateMany({ c: 'orange' }, { $set: { is_also_fruit: true } });

  // { modifiedCount: 0, matchedCount: 0, upsertedCount: 1, upsertedId: '...' }
  await collection.updateMany({ c: 'orange' }, { $set: { is_also_fruit: true } }, { upsert: true });
})();

Operations on documents are performed at the Collection level. For more information, see the Client reference.

Collection is a generic class with the default type of Document. You can specify your own type, and the object is serialized by Jackson.

Most methods have synchronous and asynchronous flavors, where the asynchronous version is suffixed by Async and returns a CompletableFuture.

// Synchronous
UpdateResult updateMany(Filter filter, Update update);
UpdateResult updateMany(Filter filter, Update update, UpdateManyOptions);

// Synchronous
CompletableFuture<UpdateResult<T>> updateManyAsync(Filter filter, Update update);
CompletableFuture<UpdateResult<T>> updateManyAsync(Filter filter, Update update, UpdateManyOptions);

Parameters:

Name Type Summary

filter

Filter

Filters to select documents. This object 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 filter clauses.

update

Update

The update prescription ot apply to the documents. For examples and a list of available operators, see [find-and-update-a-document] and Data API operators.

options

UpdateManyOptions

Contains the options for updateMany(), including the upsert flag that controls the behavior if there are no matches. If true and there are no matches, then the operation inserts one new document by applying the update to an empty document. If false and there are no matches, then the operation silently does nothing.

Returns:

UpdateResults<T> - Result of the operation with the number of documents matched (matchedCount) and updated (modifiedCount)

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 com.datastax.astra.client.model.Update;
import com.datastax.astra.client.model.UpdateManyOptions;
import com.datastax.astra.client.model.UpdateResult;
import com.datastax.astra.client.model.Updates;

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

public class UpdateMany {

    public static void main(String[] args) {
        // Given an existing collection
        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"));

        Update update = Updates.set("field1", "value1")
                .inc("field2", 1d)
                .unset("field3");

        UpdateManyOptions options =
                new UpdateManyOptions().upsert(true);

        UpdateResult result = collection.updateMany(filter, update, options);
    }
}

Find documents matching a filter condition, and then edit a property in those documents:

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 '{
  "updateMany": {
    "filter": { "status": "active" },
    "update": { "$set": { "status": "inactive" } }
  }
}' | jq

For more examples, see [update-one].

Parameters:

Name Type Summary

updateMany

command

The Data API command to update multiple documents in a collection in a database.

filter

object

Defines the criteria to selecting documents to update. 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.

update

object

The update prescription to apply to the documents. For example: {"$set": {"field": "value"}}, {"$inc": {"counter": 10}} and {"$unset": {"field": ""}}. For additional examples and a list of available operators, see [find-and-update-a-document] and Data API operators.

options.upsert

boolean

This parameter controls the behavior if there are no matches. If true and there are no matches, then the operation inserts one new document by applying the update to an empty document. If false and there are no matches, then the operation silently does nothing.

Returns:

The updateMany command returns the outcome of the operation, including the number of documents that matched the filter (matchedCount) and the number of documents that were modified (modifiedCount).

Pagination occurs if there are more than 20 matching documents. In this case, the Count values are capped at 20, and the moreData flag is set to true.

{
  "status": {
    "matchedCount": 20,
    "modifiedCount": 20,
    "moreData": true,
    "nextPageState": "NEXT_PAGE_STATE_ID"
  }
}

In the event of pagination, you must issue a subsequent request with a pageState ID to update the next page of documents that matched the filter. As long as there is a subsequent page with matching documents to update, the transaction returns a nextPageState ID, which you use as the pageState for the subsequent request.

Each paginated request is exactly the same as the original request, except for the addition of the pageState in the options object:

{
  "updateMany": {
    "filter": { "active_user": true },
    "update": { "$set": { "new_data": "new_data_value" } },
    "options": { "pageState": "*NEXT_PAGE_STATE_ID" }
  }
}

Continue issuing requests with the subsequent pageState ID until all matching documents have been updated.

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