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

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

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

Find and update a document

Find one document that matches a filter condition, apply changes to it, and then return the document itself.

This is effectively an expansion of the findOne command with additional support for update operators and related options.

  • 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:

collection.find_one_and_update(
    {"Marco": {"$exists": True}},
    {"$set": {"title": "Mr."}},
)

Locate and update a document, returning the document itself, and create a new one if no match is found:

collection.find_one_and_update(
    {"Marco": {"$exists": True}},
    {"$set": {"title": "Mr."}},
    upsert=True,
)

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

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

Returns:

Dict[str, Any] - The document that was found, either before or after the update (or a projection thereof, as requested). If no matches are found, None is returned.

Example response
{'_id': 999, 'Marco': 'Polo'}

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

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 a list of available operators, see Data API operators.

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.

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.

return_document

str

A flag controlling what document is returned. If set to ReturnDocument.BEFORE or the string "before", then the original document is returned. If set to ReturnDocument.AFTER or the string "after", then the updated document is returned. The default is "before".

max_time_ms

Optional[int]

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

Example:

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

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

collection.find_one_and_update(
    {"Marco": {"$exists": True}},
    {"$set": {"title": "Mr."}},
)
# prints: {'_id': 'a80106f2-...', 'Marco': 'Polo'}
collection.find_one_and_update(
    {"title": "Mr."},
    {"$inc": {"rank": 3}},
    projection={"title": True, "rank": True},
    return_document=astrapy.constants.ReturnDocument.AFTER,
)
# prints: {'_id': 'a80106f2-...', 'title': 'Mr.', 'rank': 3}
collection.find_one_and_update(
    {"name": "Johnny"},
    {"$set": {"rank": 0}},
    return_document=astrapy.constants.ReturnDocument.AFTER,
)
# (returns None for no matches)
collection.find_one_and_update(
    {"name": "Johnny"},
    {"$set": {"rank": 0}},
    upsert=True,
    return_document=astrapy.constants.ReturnDocument.AFTER,
)
# prints: {'_id': 'cb4ef2ab-...', 'name': 'Johnny', 'rank': 0}

For more information, see the Client reference.

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

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

Locate and update a document, returning the updated document, and create a new one if no match is found:

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

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

const docBefore = await collection.findOneAndUpdate(
  {},
  { $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 documents using filtering options.

update

UpdateFilter<Schema>

The update to apply to the selected document. For a list of available operators, see Data API operators.

options

FindOneAndUpdateOptions

The options for this operation.

Name Type Summary

returnDocument

'before' | 'after'

Specifies whether to return the original ('before') or updated ('after') document.

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.

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 document before/after the update, depending on the type of returnDocument, or null if no matches are found.

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 'Mr.'
  const updated1 = await collection.findOneAndUpdate(
    { 'Marco': 'Polo' },
    { $set: { title: 'Mr.' } },
    { returnDocument: 'after' },
  );
  console.log(updated1?.title);

  // Prints { _id: ..., title: 'Mr.', rank: 3 }
  const updated2 = await collection.findOneAndUpdate(
    { title: 'Mr.' },
    { $inc: { rank: 3 } },
    { projection: { title: 1, rank: 1 }, returnDocument: 'after' },
  );
  console.log(updated2);

  // Prints null
  const updated3 = await collection.findOneAndUpdate(
    { name: 'Johnny' },
    { $set: { rank: 0 } },
    { returnDocument: 'after' },
  );
  console.log(updated3);

  // Prints { _id: ..., name: 'Johnny', rank: 0 }
  const updated4 = await collection.findOneAndUpdate(
    { name: 'Johnny' },
    { $set: { rank: 0 } },
    { upsert: true, returnDocument: 'after' },
  );
  console.log(updated4);
})();

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

// Synchronous
CompletableFuture<Optional<T>> findOneAndUpdateAsync(Filter filter, Update update);

Returns:

Optional<T> - Return the working document matching the filter or Optional.empty() if no document is found.

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. For a list of available operators, see Data API operators. For examples and options, including projection and sort, see Find documents using filtering options.

update

Update

The update prescription to apply to the document. For a list of available operators, see Data API operators.

To build the different parts of the requests, a set of helper classes are provided These are suffixed by an s, such as Filters for Filter and Updates for Update.

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

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.Updates;

import java.util.Optional;

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

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

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

        Optional<Document> doc = collection.findOneAndUpdate(filter, update);

    }
}

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

This example uses the $currentDate update operator to set a property to the current date:

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 '{
  "findOneAndUpdate": {
    "filter": { "_id": "doc1" },
    "update": {
      "$currentDate": {
        "createdAt": true
        }
      }
    }
}' | jq
More update operator examples

Unset a property:

"findOneAndUpdate": {
  "filter": {
    "_id": "12"
  },
  "update": { "$unset": { "amount": "" } },
  "options": { "returnDocument": "after" }
}

Increment a value:

"findOneAndUpdate": {
  "filter": {
    "_id": "12"
  },
  "update": { "$inc": { "counter": 1 } },
  "options": { "returnDocument": "after" }
}

Add an element to a specific position in an array:

"findOneAndUpdate": {
  "filter": {
    "_id": "12"
  },
  "update": { "$push": { "tags": { "$each": [ "new1", "new2" ], "$position": 0 } } },
  "options": { "returnDocument": "after" }
}

Rename a field:

"findOneAndUpdate": {
  "filter": {
    "_id": "12"
  },
  "update": { "$rename": { "old_field": "new_field", "other_old_field": "other_new_field" } },
  "options": { "returnDocument": "after" }
}

Locate and update a document, returning the updated document, and create a new one if no match is found:

"findOneAndUpdate": {
  "filter": {
    "_id": "14"
  },
  "update": { "$set": { "min_col": 2, "max_col": 99 } },
  "options": { "returnDocument": "after", "upsert": true }
}

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

"findOneAndUpdate": {
  "filter": {
    "_id": "27"
  },
  "update": {
    "$currentDate": {
      "field": true
    },
    "$setOnInsert": {
      "customer.name": "James B."
    }
  },
  "options": {
    "returnDocument": "after",
    "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"
    }
  },
  "options": {
    "returnDocument": "after"
  }
}

Parameters:

Name Type Summary

findOneAndUpdate

command

Data API command to find one document based on a query and then run an update operation on the document’s properties.

sort, filter

object

Search criteria to find the document to update. For a list of available operators, see Data API operators. For examples and parameters, see Find a document and Sort operations.

update

object

The update prescription to apply to the document using Data API operators. For example: {"$set": {"field": "value}}, {"$inc": {"counter": 10}} and {"$unset": {"field": ""}}.

projection

object

See Find a document and Projection operations.

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.

options.returnDocument

string

A flag controlling what document is returned. If set to "before", then the original document is returned. If set to "after", then the updated document is returned. The default is "before".

Returns:

A successful response contains a data object and a status object:

  • The data object contains a single document object representing either the original or modified document, based on the returnDocument parameter.

    "data": {
      "document": {
        "_id": "5",
        "purchase_type": "Online",
        "$vector": [0.25, 0.045, 0.38, 0.31, 0.67],
        "customer": "David C.",
        "amount": 94990
      }
    }
  • The status object contains the matchedCount and modifiedCount fields, which indicate the number of documents that matched the filter and the number of documents that were modified, respectively. If the update operation didn’t change any parameters in the matching document, then the modifiedCount is 0.

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

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 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 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]},
)

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=...)

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

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.

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

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);

Returns:

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

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.

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

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

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

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

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=...)

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

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.

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

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

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);

Returns:

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

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

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.

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

For more examples, see Update a document.

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

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?

© 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