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

Update a document

updateOne is similar to findOneAndUpdate, 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 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 edit a property in that document:

update_result = collection.update_one(
    {"_id": 456},
    {"$set": {"name": "John Smith"}},
)

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

update_result = collection.update_one(
    {"_id": 456},
    {"$set": {"name": "John Smith"}},
    upsert=True,
)

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

update_result = collection.update_one(
    {},
    {"$set": {"best_match": True}},
    sort={"$vector": [0.1, 0.2, 0.3]},
)

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 a document.

update

Dict[str, Any]

The update prescription to apply to the document, 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.

sort

Optional[Dict[str, Any]]

See Find a document and Sort clauses.

upsert

bool = False

This parameter controls the behavior if there are no matches. If true and there are no matches, then the operation inserts a 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 underlying HTTP request. This method uses the collection-level timeout by default.

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': 1, 'updatedExisting': True, 'ok': 1.0, 'nModified': 1}, raw_results=...)

Example:

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

collection.insert_one({"Marco": "Polo"})

collection.update_one({"Marco": {"$exists": True}}, {"$inc": {"rank": 3}})
# prints: UpdateResult(update_info={'n': 1, 'updatedExisting': True, 'ok': 1.0, 'nModified': 1}, raw_results=...)
collection.update_one({"Mirko": {"$exists": True}}, {"$inc": {"rank": 3}})
# prints: UpdateResult(update_info={'n': 0, 'updatedExisting': False, 'ok': 1.0, 'nModified': 0}, raw_results=...)
collection.update_one(
    {"Mirko": {"$exists": True}},
    {"$inc": {"rank": 3}},
    upsert=True,
)
# prints: UpdateResult(update_info={'n': 1, 'updatedExisting': False, 'ok': 1.0, 'nModified': 0, 'upserted': '2a45ff60-...'}, raw_results=...)

For more information, see the Client reference.

Find a document matching a filter condition, and then edit a property in that document:

const result = await collection.updateOne(
  { $and: [{ name: 'Jesse' }, { gender: 'M' }] },
  { $set: { title: 'Mr.' } },
);

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

const result = await collection.updateOne(
  { $and: [{ name: 'Jesse' }, { gender: 'M' }] },
  { $set: { title: 'Mr.' } },
  { upsert: true },
);

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

const result = await collection.updateOne(
  {},
  { $set: { bestMatch: true } },
  { sort: { $vector: [0.1, 0.2, 0.3] } },
);

Parameters:

Name Type Summary

filter

Filter<Schema>

A filter to select the document to update. For a list of available operators, see Data API operators. For additional examples, see Find a document.

update

UpdateFilter<Schema>

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

options?

UpdateOneOptions

The options for this operation.

Options (UpdateOneOptions):

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 a new document by applying the update to an empty document. If false and there are no matches, then the operation silently does nothing.

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.

Returns:

Promise<UpdateOneResult<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 a document
  await collection.insertOne({ 'Marco': 'Polo' });

  // Prints 1
  const updated1 = await collection.updateOne(
    { 'Marco': 'Polo' },
    { $set: { title: 'Mr.' } },
  );
  console.log(updated1?.modifiedCount);

  // Prints 0 0
  const updated2 = await collection.updateOne(
    { name: 'Johnny' },
    { $set: { rank: 0 } },
  );
  console.log(updated2.matchedCount, updated2?.upsertedCount);

  // Prints 0 1
  const updated3 = await collection.updateOne(
    { name: 'Johnny' },
    { $set: { rank: 0 } },
    { upsert: true },
  );
  console.log(updated3.matchedCount, updated3?.upsertedCount);
})();

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
UpdateResult updateOne(Filter filter, Update update);

// Asynchronous
CompletableFuture<UpdateResult<T>> updateOneAsync(Filter filter, Update update);

Parameters:

Name Type Summary

filter

Filter

Criteria list to filter the document. The filter is a JSON object that can contain any valid Data API filter expression.

update

Update

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

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

import java.util.Optional;

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

public class UpdateOne {
    // 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"));

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

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

Find a document matching a filter condition, and then edit a property in that document:

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 '{
  "updateOne": {
    "filter": {
      "_id": "14"
    },
    "update": { "$set": { "name": "Xiala" } }
  }
}' | jq

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

"updateOne": {
  "filter": {
    "_id": "16"
  },
  "update": { "$set": { "name": "Serapio" } },
  "options": { "upsert": true }
}

If an upsert occurs, use the $setOnInsert operator to assign additional properties to the new document:

"findOneAndUpdate": {
  "filter": {
    "_id": "16"
  },
  "update": {
    "$currentDate": {
      "field": true
    },
    "$setOnInsert": {
      "customer.name": "James B."
    }
  },
  "options": {
    "upsert": true
  }
}

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

"findOneAndUpdate": {
  "sort": {
    "$vector": [0.1, 0.2, 0.3]
  },
  "update": {
    "$set": {
      "status": "active"
    }
  }
}

Parameters:

Name Type Summary

updateOne

command

The Data API command to updates a single document matching a query.

sort, filter

object

Used to select the document to be updated. For a list of available operators, see Data API operators. For sort and filter examples, see Find a document and Sort clauses.

update

object

The update prescription to apply to the document. 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.

options.upsert

boolean

This parameter controls the behavior if there are no matches. If true and there are no matches, then the operation inserts a 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 updateOne command returns only the outcome of the operation, including the number of documents that matched the filter (matchedCount) and the number of documents that were modified (modifiedCount):

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

Example:

The following example uses the $set update operator to set the value of a property (which uses the nested notation customer.name) to a new value. In this example, zodiac can be a nested document or a property within the main document, and animal is a property within zodiac. The operation intends to update the nested animal field to lion.

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 '{
  "updateOne": {
    "filter": {
      "_id": "18"
    },
    "update": { "$set": { "zodiac.animal": "lion" } }
  }
}' | jq

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