Update documents

Finds documents in a collection using filter clauses, and then updates properties in those documents. Optionally, if no document matches the filter, inserts a new document.

This method does not support sort parameters, including vector search. If you want to use sort parameters to find documents, use the method to find documents instead. Then, use the method to update a single document to update the found documents by ID.

Result

  • Python

  • TypeScript

  • Java

  • curl

Updates documents that match the specified parameters and returns an UpdateResult object that includes details about the success of the operation, including the number of documents that were found and the number of documents that were modified.

Example response:

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

If specified, the method inserts a new document if no document matches the filter.

Example response if a new document was inserted:

UpdateResult(update_info={'n': 1, 'updatedExisting': False, 'ok': 1.0, 'nModified': 0, 'upserted': '91838621-160d-4a35-8386-21160d2a3580'}, raw_results=...)

Updates documents that match the specified parameters and returns a promise that resolves to an UpdateManyResult<Schema> object that includes details about the success of the operation, including the number of documents that were found and the number of documents that were modified.

Example resolved response:

{
  modifiedCount: 2,
  matchedCount: 3,
  upsertedCount: 0
}

If specified, the method inserts a new document if no document matches the filter.

Example resolved response if a new document was inserted:

{
  modifiedCount: 0,
  matchedCount: 0,
  upsertedCount: 1,
  upsertedId: '5be853e7-b5d3-401b-a853-e7b5d3801bae'
}

Updates documents that match the specified parameters and returns UpdateResults<T>, which indicates the number of documents that were found and the number of documents that were modified.

If specified, the method inserts a new document if no document matches the filter. In this case, the response also includes the _id of the inserted document.

Updates documents that match the specified parameters and returns an object that includes details about the success of the operation, including the number of documents that were found and the number of documents that were modified.

Example response:

{
  "status":{
    "matchedCount":3,
    "modifiedCount":2
  }
}

If specified, the method inserts a new document if no document matches the filter.

Example response if a new document was inserted:

{
  "status":{
    "upsertedId":"1a69f13b-0331-4e85-a9f1-3b0331fe854b",
    "matchedCount":0,
    "modifiedCount":0
  }
}

If more than 20 documents match the specified filter parameters, only the first 20 documents will be updated. In this case, the status.matchedCount and status.modifiedCount are capped at 20, the status.moreData value is true, and the status.nextPageState value is the ID of the next page of data. To update the next batch of 20 documents, you must send a request with the nextPageState value from your previous request. For an example, see Update more than 20 documents.

Example response if more documents match the filter than were updated:

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

Parameters

  • Python

  • TypeScript

  • Java

  • curl

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 and examples, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

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.

Name Type Summary

filter

Filter<Schema>

A filter to select the documents to update. For a list of available operators and examples, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

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.

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 and examples, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

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.

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 and examples, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

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.

Examples

The following examples demonstrate how to update documents in a collection.

Update documents that match a filter

You can use a filter to find documents that match specific criteria. For example, you can find documents with an isCheckedOut value of false and a numberOfPages value less than 300.

For a list of available filter operators and more examples, see Data API operators.

Filters can use only indexed fields. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in a filter.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Update documents
result = collection.update_many(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    {"$set": {"color": "blue"}}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Update documents
(async function () {
  const result = await collection.updateMany(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {$set: {color: "blue"}}
  );

  console.log(result);
})();
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 java.util.Optional;

public class UpdateMany {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Update documents
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates.set("color", "blue");
        UpdateResult result = collection.updateMany(filter, update);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}
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": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "update": { "$set": { "color": "blue" } }
  }
}'

Update multiple properties

You can combine multiple operators and properties in a single call. For the full list of operators, see Data API operators.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Update documents
result = collection.update_many(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    {
        "$set": {
            "color": "blue",
            "classes": ["biology", "algebra", "swimming"]
            },
        "$unset": {
            "phone": ""
        },
        "$inc": {
          "age": 1
        }
    }
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Update documents
(async function () {
  const result = await collection.updateMany(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {
      $set: {
        color: "blue",
        classes: ["biology", "algebra", "swimming"]
      },
      $unset: {
        phone: ""
      },
      $inc: {
        age: 1
      }
    }
  );

  console.log(result);
})();
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.UpdateResult;
import com.datastax.astra.client.model.Updates;

import java.util.Arrays;
import java.util.Optional;

public class UpdateMany {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Update documents
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates
          .set("color", "blue")
          .set("classes", Arrays.asList("biology", "algebra", "swimming"))
          .unset("phone")
          .inc("age", 1.0);
        UpdateResult result = collection.updateMany(filter, update);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}
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": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "update": {
        "$set": {
            "color": "blue",
            "classes": ["biology", "algebra", "swimming"]
            },
        "$unset": {
            "phone": ""
        },
        "$inc": {
          "age": 1
        }
    }
  }
}'

Update nested properties

To update a nested property, use dot notation. For example, field.subfield.subsubfield.

To update an item in a list, specify a numeric index. For example, listProperty.3.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Update documents
result = collection.update_many(
  {
      "$and": [
          {"isCheckedOut": False},
          {"numberOfPages": {"$lt": 300}},
      ]
  },
  {
    "$set": {
      "color": "blue",
      "address.city": "Austin",
      "classes.2": "biology"
    }
  }
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Update documents
(async function () {
  const result = await collection.updateMany(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {
      $set: {
        color: "blue",
        "address.city": "Austin",
        "classes.2": "biology"
      }
    }
  );

  console.log(result);
})();
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.UpdateResult;
import com.datastax.astra.client.model.Updates;

import java.util.Optional;

public class UpdateMany {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Update documents
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates
          .set("color", "blue")
          .set("address.city", "Austin")
          .set("classes.2", "biology");
        UpdateResult result = collection.updateMany(filter, update);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}
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": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "update": {
        "$set": {
            "color": "blue",
            "address.city": "Austin",
            "classes.2": "biology"
            }
    }
  }
}'

Insert a new document if no matching document exists

If no document matches the filter criteria, you can use upsert to specify that a new document should be created.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Update documents
result = collection.update_many(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    {"$set": {"color": "blue"}},
    upsert=True,
)

print(result)

You can also use the setOnInsert operator specify additional fields to set if a new document is created:

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Update documents
result = collection.update_many(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    {
      "$set": {"color": "blue"},
      "$setOnInsert": {
          "customer.name": "James"
        }
    },
    upsert=True,
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Update documents
(async function () {
  const result = await collection.updateMany(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    { $set: {color: "blue"} },
    { upsert: true },
  );

  console.log(result);
})();

You can also use the setOnInsert operator specify additional fields to set if a new document is created:

import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Update documents
(async function () {
  const result = await collection.updateMany(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {
      $set: {color: "blue"},
      $setOnInsert: {
        "customer.name": "James"
      }
    },
    { upsert: true },
  );

  console.log(result);
})();
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 java.util.Optional;

public class UpdateMany {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Update documents
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates.set("color", "blue");
        UpdateManyOptions options = new UpdateManyOptions().upsert(true);
        UpdateResult result = collection.updateMany(filter, update, options);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
        System.out.println(result.getUpsertedId());
    }
}
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": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "update": { "$set": { "color": "blue" } },
    "options": { "upsert": true }
  }
}'

You can also use the setOnInsert operator specify additional fields to set if a new document is created:

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": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "update": {
      "$set": { "color": "blue" },
      "$setOnInsert": {
        "customer.name": "James"
      }
    },
    "options": { "upsert": true }
  }
}'

Update more than 20 documents

  • Python

  • TypeScript

  • Java

  • curl

The client automatically issues multiple Data API HTTP requests to update all documents that match your filter.

The client automatically issues multiple Data API HTTP requests to update all documents that match your filter.

The client automatically issues multiple Data API HTTP requests to update all documents that match your filter.

You can only update 20 documents per HTTP request.

If additional documents match your filter but were not updated, the response will include a status.moreData value of true and a non-null status.nextPageState value.

To update the next batch of 20 documents, you must send a request with the nextPageState value from your previous request. For example:

  1. Send an initial request

    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": {"$and": [
          {"isCheckedOut": false},
          {"numberOfPages": {"$lt": 300}}
        ]},
        "update": { "$set": { "color": "blue" } }
      }
    }'
  2. Get the status.nextPageState value from the response

    {
      "status":{
        "matchedCount":20,
        "nextPageState":"LQAAAAEBAAAAJGU5ZTY4ODViLTM2MDEtNDhhMy1hNjg4LTViMzYwMWQ4YTNmZADwf///6wA=",
        "modifiedCount":20,
        "moreData":true
      }
    }
  3. Use the status.nextPageState from the previous response to request the next page of results.

    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": {"$and": [
          {"isCheckedOut": false},
          {"numberOfPages": {"$lt": 300}}
        ]},
        "update": { "$set": { "color": "blue" } },
        "options": {
          "pageState": "NEXT_PAGE_STATE_FROM_PRIOR_RESPONSE"
        }
      }
    }'
  4. Once status.nextPageState is omitted from the response, you have updated all matching documents.

    {
      "status":{
        "matchedCount":0,
        "modifiedCount":0
      }
    }

Client reference

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the client reference.

For more information, see the client reference.

For more information, see the client reference.

Client reference documentation is not applicable for HTTP.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | Privacy policy | Terms of use | Manage Privacy Choices

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