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.
For general information about working with documents, including common operations and operators, see the Documents reference.
Prerequisites
-
Review the prerequisites and other information in Intro to Astra DB APIs.
-
Create a Serverless (Vector) database.
-
Learn how to instantiate a
DataAPIClient
object and connect to your database.
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]},
)
Parameters:
Name | Type | Summary |
---|---|---|
|
|
A predicate expressed as a dictionary according to the Data API filter syntax.
For example: |
|
|
The update prescription to apply to the document, expressed as a dictionary as per Data API syntax.
For example: |
|
|
See Find a document and Projection operations. |
|
|
See Find a document and Sort operations. |
|
|
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 |
|
|
A flag controlling what document is returned.
If set to |
|
|
A timeout, in milliseconds, for the underlying HTTP request. This method uses the collection-level timeout by default. |
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'}
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 |
---|---|---|
|
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. |
|
|
The update to apply to the selected document. For a list of available operators, see Data API operators. |
|
|
The options for this operation. |
Options (FindOneAndUpdateOptions
):
Name | Type | Summary |
---|---|---|
|
Specifies whether to return the original ( |
|
|
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 |
|
See Find a document and Projection operations. |
||
See Find a document and Sort operations. |
||
|
The maximum time in milliseconds that the client should wait for the operation to complete each underlying HTTP request. |
|
|
When true, returns |
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);
Parameters:
Name | Type | Summary |
---|---|---|
|
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 |
|
|
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
|
Returns:
Optional<T>
- Return the working document matching the filter or Optional.empty()
if no document is found.
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" }
}
Use $position
to add an element to a specific position in an array.
$position
is only valid with $push
, and $each
is required, even if you want to insert a single item at the specified position.
"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 |
---|---|---|
|
|
Data API command to find one document based on a query and then run an update operation on the document’s properties. |
|
|
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. |
|
|
The update prescription to apply to the document using Data API operators.
For example: |
|
|
See Find a document and Projection operations. |
|
|
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 |
|
|
A flag controlling what document is returned.
If set to |
Returns:
A successful response contains a data
object and a status
object:
-
The
data
object contains a singledocument
object representing either the original or modified document, based on thereturnDocument
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 thematchedCount
andmodifiedCount
fields, which indicate the number of documents that matched the filter and the number of documents that were modified, respectively. If theupdate
operation didn’t change any parameters in the matching document, then themodifiedCount
is0
."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]},
)
Parameters:
Name | Type | Summary |
---|---|---|
|
|
A predicate expressed as a dictionary according to the Data API filter syntax.
For example: |
|
|
The update prescription to apply to the document, expressed as a dictionary as per Data API syntax.
For example: |
|
|
See Find a document and Sort operations. |
|
|
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 |
|
|
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 |
---|---|---|
|
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. |
|
|
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. |
|
|
The options for this operation. |
Options (UpdateOneOptions
):
Name | Type | Summary |
---|---|---|
|
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 |
|
See Find a document and Sort operations. |
||
|
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 |
---|---|---|
|
Criteria list to filter the document. The filter is a JSON object that can contain any valid Data API filter expression. |
|
|
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 --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 |
---|---|---|
|
|
The Data API command to updates a single document matching a query. |
|
|
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. |
|
|
The update prescription to apply to the document.
For example: |
|
|
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 |
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.
Parameters:
Name | Type | Summary |
---|---|---|
|
|
A predicate expressed as a dictionary according to the Data API filter syntax.
For example: |
|
|
The update prescription to apply to the documents, expressed as a dictionary as per Data API syntax.
For example: |
|
|
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 |
|
|
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 a document.
Parameters:
Name | Type | Summary |
---|---|---|
|
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. |
|
|
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. |
|
|
The options for this operation. |
Options (UpdateManyOptions
):
Name | Type | Summary |
---|---|---|
|
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 |
|
|
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 |
---|---|---|
|
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. |
|
|
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. |
|
|
Contains the options for |
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 --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 |
---|---|---|
|
|
The Data API command to update multiple documents in a collection in a database. |
|
|
Defines the criteria to selecting documents to update.
For example: |
|
|
The update prescription to apply to the documents.
For example: |
|
|
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 |
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.