Find and update a document

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

This method and the method to update a document have the same database effect but differ in their return value. This method returns the document that was found and updated. The method to update a document returns details about the success of the update.

Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart.

Result

  • Python

  • TypeScript

  • Java

  • curl

Updates a document that matches the specified parameters, and returns a dictionary representation of the document. If no document was found, returns None.

The method parameters control whether the returned document reflects the original or updated values.

The fields included in the returned document depend on the projection specified in the method.

If an upsert is requested, the method inserts a new document if no document matches the filter.

Example response:

{'_id': 101, 'name': 'John Doe'}

Updates a document that matches the specified parameters, and returns a promise that resolves to the document. If no document was found, returns returns a promise that resolves to null.

The method parameters control whether the returned document reflects the original or updated values.

The fields included in the returned document depend on the projection specified in the method.

If an upsert is requested, the method inserts a new document if no document matches the filter.

Example resolved response:

{_id: 101, name: 'John Doe'}

Updates a document that matches the specified parameters, and returns the document (Optional<T>). If no document was found, returns returns Optional.empty().

The method parameters control whether the returned document reflects the original or updated values.

The fields included in the returned document depend on the projection specified in the method.

If an upsert is requested, the method inserts a new document if no document matches the filter.

Updates a document that matches the specified parameters, and returns a dictionary representation of the document. If no document was found, returns null instead of a dictionary representation of the document.

The method parameters control whether the returned document reflects the original or updated values.

The fields included in the returned document depend on the projection specified in the method.

The response also includes details about the success of the operation, such as the number of documents that were modified.

If an upsert is requested, the method inserts a new document if no document matches the filter.

Example response:

{
  "data": {
    "document": {
      "_id":"101",
      "name":"John Doe"
    }
  },
  "status":{
    "matchedCount":1,
    "modifiedCount":1
  }
}

Example response if no document was found:

{
  "data":{
    "document":null
  },
  "status":{
    "matchedCount":0,
    "modifiedCount":0
  }
}

Example response if a new document was inserted:

{
  "data":{
    "document":null
  },
  "status":{
    "upsertedId":"7d690267-28f5-47e8-a902-6728f587e84e",
    "matchedCount":0,
    "modifiedCount":0
  }
}

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Use the find_one_and_update method, which belongs to the astrapy.Collection class.

Method signature
find_one_and_update(
  filter: Dict[str, Any],
  update: Dict[str, Any],
  *,
  projection: Dict[str, bool],
  sort: Dict[str, Any],
  upsert: bool,
  return_document: str,
  general_method_timeout_ms: int,
  request_timeout_ms: int,
  timeout_ms: int,
) -> Dict[str, Any]
Name Type Summary

filter

Dict[str, Any]

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match this filter criteria.

For a list of available filter operators and more examples, see Filter operators for collections.

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.

update

Dict[str, Any]

An object that defines the updates using Data API operators.

For a list of available operators and more examples, see Update operators for collections.

projection

Dict[str, bool]

Optional. Controls which fields are included or excluded in the returned document.

For more information, see Projections for collections.

Default: The default projection for the collection. Certain fields, like $vector and $vectorize, are excluded by default. Certain fields, like _id, are included by default.

sort

Dict[str, Any]

Optional. Sorts documents by one or more fields, or performs a vector search.

For more information, see Sort clauses for collections.

Sort 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 queries.

upsert

bool

Optional. Whether to insert a new document if no document matches the filter criteria.

Default: False

return_document

str

Optional. Controls whether the response reflects the document before or after the update.

Can be one of:

Default: ReturnDocument.BEFORE

general_method_timeout_ms

int

Optional. The maximum time, in milliseconds, that the client should wait for the underlying HTTP request.

Default: The default value for the collection. This default is 30 seconds unless you specified a different default when you initialized the Collection or DataAPIClient object. For more information, see Timeout options.

request_timeout_ms

int

Optional. An alias for general_method_timeout_ms. Since this method issues a single HTTP request, general_method_timeout_ms and request_timeout_ms are equivalent.

timeout_ms

int

Optional. An alias for general_method_timeout_ms.

Use the findOneAndUpdate method, which belongs to the Collection class.

Method signature
async findOneAndUpdate(
  filter: CollectionFilter<Schema>,
  update: CollectionUpdateFilter<Schema>,
  options?: {
    returnDocument?: 'before' | 'after',
    upsert?: boolean,
    sort?: Sort,
    projection?: Projection,
    includeResultMetadata?: boolean,
    timeout?: number | TimeoutDescriptor,
  },
): Schema | null
Name Type Summary

filter

CollectionFilter<Schema>

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match this filter criteria.

For a list of available filter operators and more examples, see Filter operators for collections.

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.

update

CollectionUpdateFilter<Schema>

An object that defines the updates using Data API operators.

For a list of available operators and more examples, see Update operators for collections.

options

CollectionFindOneAndUpdateOptions

Optional. The options for this operation. See the options table for more details.

Properties of options
Name Type Summary

returnDocument

string

Optional. Controls whether the response reflects the document before or after the update.

Can be one of:

  • "before"

  • "after"

Default: "before"

upsert

boolean

Optional. Whether to insert a new document if no document matches the filter criteria.

Default: False

projection

Projection

Optional. Controls which fields are included or excluded in the returned document.

For more information, see Projections for collections.

Default: The default projection for the collection. Certain fields, like $vector and $vectorize, are excluded by default. Certain fields, like _id, are included by default.

sort

Sort

Optional. Sorts documents by one or more fields, or performs a vector search.

For more information, see Sort clauses for collections.

Sort 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 queries.

For vector searches, this parameter can use either $vector or $vectorize.

includeResultMetadata

boolean

Whether to include details about the success of the operation in the response.

Default: False

timeout

number | TimeoutDescriptor

Optional.

The timeout(s) to apply to this method. You can specify requestTimeoutMs and generalMethodTimeoutMs. Since this method issues a single HTTP request, these timeouts are equivalent.

Details about the timeout parameter

The TimeoutDescriptor object can contain these properties:

  • requestTimeoutMs (number): The maximum time, in milliseconds, that the client should wait for each underlying HTTP request. Default: The default value for the collection. This default is 10 seconds unless you specified a different default when you initialized the Collection or DataAPIClient object.

  • generalMethodTimeoutMs (number): The maximum time, in milliseconds, that the whole operation can take. Since this method issues a single HTTP request, generalMethodTimeoutMs and requestTimeoutMs are equivalent. If you specify both, the minimum of the two will be used. Default: The default value for the collection. This default is 30 seconds unless you specified a different default when you initialized the Collection or DataAPIClient object.

If you specify a number instead of a TimeoutDescriptor object, that number will be applied to both requestTimeoutMs and generalMethodTimeoutMs.

Use the findOneAndUpdate method, which belongs to the com.datastax.astra.client.Collection class.

Method signature
Optional<T> findOneAndUpdate(
  Filter filter,
  Update update
)
Optional<T> findOneAndUpdate(
  Filter filter,
  Update update,
  CollectionFindOneAndUpdateOptions options
)
Name Type Summary

filter

Filter

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match this filter criteria.

For a list of available filter operators and more examples, see Filter operators for collections.

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.

update

Update

An object that defines the updates using Data API operators.

For a list of available operators and more examples, see Update operators for collections.

options

CollectionFindOneAndUpdateOptions

Optional. The options for this operation. See the methods of the CollectionFindOneAndUpdateOptions class for more details.

Methods of the CollectionFindOneAndUpdateOptions class:
Method Parameters Summary

sort()

float[] | String | Sort | Map<String, Object>

Optional. Sorts documents by one or more fields, or performs a vector search.

For more information, see Sort clauses for collections.

Sort 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 queries.

For vector searches, this parameter can use either $vector or $vectorize.

projection()

Projection

Optional. Controls which fields are included or excluded in the returned document.

For more information, see Projections for collections.

Default: The default projection for the collection. Certain fields, like $vector and $vectorize, are excluded by default. Certain fields, like _id, are included by default.

upsert()

boolean

Optional. Whether to insert a new document if no document matches the filter criteria.

Default: False

returnDocumentAfter()

None

Optional. The response reflects the document after the update.

returnDocumentBefore()

None

Optional. The response reflects the document before the update.

This is the default unless returnDocumentAfter() is used.

Use the findOneAndUpdate command.

Command signature
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/COLLECTION_NAME" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOneAndUpdate": {
    "filter": FILTER,
    "update": UPDATE,
    "sort": SORT,
    "projection": PROJECTION,
    "options": {
      "upsert": BOOLEAN,
      "returnDocument": RETURN_DOCUMENT_DIRECTIVE
    }
  }
}'
Name Type Summary

filter

object

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match this filter criteria.

For a list of available filter operators and more examples, see Filter operators for collections.

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.

sort

object

Optional. Sorts documents by one or more fields, or performs a vector search.

For more information, see Sort clauses for collections.

Sort 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 queries.

For vector searches, this parameter can use either $vector or $vectorize.

update

object

An object that defines the updates using Data API operators.

For a list of available operators and more examples, see Update operators for collections.

projection

object

Optional. Controls which fields are included or excluded in the returned document.

For more information, see Projections for collections.

Default: The default projection for the collection. Certain fields, like $vector and $vectorize, are excluded by default. Certain fields, like _id, are included by default.

options

object

Optional. The options for this operation. See the options table for more details.

Properties of options:

upsert

boolean

Optional. Whether to insert a new document if no document matches the filter criteria.

Default: False

returnDocument

string

Optional. Controls whether the response reflects the document before or after the update.

Can be one of:

  • "before"

  • "after"

Default: "before"

Examples

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

Update a document by ID

All documents have a unique _id property. You can use a filter to find a document with a specific _id, and then update that document.

  • 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 a document
result = collection.find_one_and_update(
    {"_id": "101"},
    {"$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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    { _id: "101" },
    {$set: {color: "blue"}}
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;

import java.util.Optional;

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.eq("_id", "101");
        Update update = Updates.set("color", "blue");
        Optional<Document> result = collection.findOneAndUpdate(filter, update);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": {
      "_id": "101"
    },
    "update": { "$set": { "color": "blue" } }
  }
}'

Update a document that matches a filter

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

For a list of available filter operators and more examples, see Filter operators for collections.

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 a document
result = collection.find_one_and_update(
    {
        "$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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {$set: {color: "blue"}}
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;

import java.util.Optional;

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates.set("color", "blue");
        Optional<Document> result = collection.findOneAndUpdate(filter, update);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "update": { "$set": { "color": "blue" } }
  }
}'

Update a document that is most similar to a search vector

To find the document whose $vector value is most similar to a given vector, use a sort with the vector embeddings that you want to match. For more information, see Find data with vector search.

Vector search is only available for vector-enabled collections. For more information, see $vector and $vectorize in collections.

  • 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 a document
result = collection.find_one_and_update(
    {},
    {"$set": {"color": "blue"}},
    sort={"$vector": [0.1, 0.2, 0.3]},
)

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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    {},
    {$set: {color: "blue"}},
    { sort: { $vector: [0.1, 0.2, 0.3] } },
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneAndUpdateOptions;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;
import com.datastax.astra.client.core.query.Sort;

import java.util.Optional;

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates.set("color", "blue");
        CollectionFindOneAndUpdateOptions options = new CollectionFindOneAndUpdateOptions()
            .sort(Sort.vector(new float[] {0.12f, 0.52f, 0.32f}))
        Optional<Document> result = collection.findOneAndUpdate(filter, update, options);
        System.out.println(result);
    }
}

You can provide the search vector as an array of floats, or you can use $binary to provide the search vector as a Base64-encoded string. $binary can be more performant.

  • Array of floats

  • $binary

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 '{
  "findOneAndUpdate": {
    "sort": {
      "$vector": [.12, .52, .32]
    },
    "update": { "$set": { "color": "blue" } }
  }
}'
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 '{
  "findOneAndUpdate": {
    "sort": {
      "$vector": {"$binary": "PfXCjz8FHrg+o9cK"}
    },
    "update": { "$set": { "color": "blue" } }
  }
}'

Update a document that is most similar to a search string

To find the document whose $vector value is most similar to the $vector value of a given search string, use a sort with the search string that you want to vectorize and match. For more information, see Find data with vector search.

Vector search with vectorize is only available for collections that have vectorize enabled. For more information, see $vector and $vectorize in collections.

  • 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 a document
result = collection.find_one_and_update(
    {},
    {"$set": {"color": "blue"}},
    sort={"$vectorize": "Text to vectorize"}
)

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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    {},
    {$set: {color: "blue"}},
    { sort: { $vectorize: "Text to vectorize" } }
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneAndUpdateOptions;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;
import com.datastax.astra.client.core.query.Sort;

import java.util.Optional;

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates.set("color", "blue");
        CollectionFindOneAndUpdateOptions options = new CollectionFindOneAndUpdateOptions()
            .sort(Sort.vectorize("Text to vectorize"));
        Optional<Document> result = collection.findOneAndUpdate(filter, update, options);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "sort": { "$vectorize": "Text to vectorize" },
    "update": { "$set": { "color": "blue" } }
  }
}'

Update a document after applying a non-vector sort

You can use a sort clause to sort documents by one or more fields.

For more information, see Sort clauses for collections.

Sort 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 queries.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient
from astrapy.constants import SortMode

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

# Find a document
result = collection.find_one_and_update(
    {"metadata.language": "English"},
    {"$set": {"color": "blue"}},
    sort={
        "rating": SortMode.ASCENDING,
        "title": SortMode.DESCENDING,
    }
)

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

// Find a document
(async function () {
  const result = await collection.findOneAndUpdate(
    { "metadata.language": "English" },
    {$set: {color: "blue"}},
    { sort: {
      rating: 1, // ascending
      title: -1 // descending
    } }
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneAndUpdateOptions;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;
import com.datastax.astra.client.core.query.Sort;

import java.util.Optional;

public class FindOneAndUpdate {

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

        // Find a document
        Filter filter = Filters.eq("metadata.language", "English");
        CollectionFindOneAndUpdateOptions options = new CollectionFindOneAndUpdateOptions()
            .sort(Sort.ascending("rating"), Sort.descending("title"));
        Update update = Updates.set("color", "blue");
        Optional<Document> result = collection.findOneAndUpdate(filter, update, options);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": { "metadata.language": "English" },
    "update": { "$set": { "color": "blue" } },
    "sort": {
      "rating": 1,
      "title": -1
    }
  }
}'

Update multiple properties

You can combine multiple operators and properties in a single request. For the full list of operators, see Update operators for collections.

  • 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 a document
result = collection.find_one_and_update(
    {"_id": "101"},
    {
        "$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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    { _id: '101' },
    {
      $set: {
        color: "blue",
        classes: ["biology", "algebra", "swimming"]
      },
      $unset: {
        phone: ""
      },
      $inc: {
        age: 1
      }
    }
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;

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

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.eq("_id", "101");
        Update update = Updates
          .set("color", "blue")
          .set("classes", Arrays.asList("biology", "algebra", "swimming"))
          .unset("phone")
          .inc("age", 1.0);
        Optional<Document> result = collection.findOneAndUpdate(filter, update);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": {
      "_id": "101"
    },
    "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 a document
result = collection.find_one_and_update(
  {"_id": "101"},
  {
    "$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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    { _id: '101' },
    {
      $set: {
        color: "blue",
        "address.city": "Austin",
        "classes.2": "biology"
      }
    }
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;

import java.util.Optional;

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.eq("_id", "101");
        Update update = Updates
          .set("color", "blue")
          .set("address.city", "Austin")
          .set("classes.2", "biology");
        Optional<Document> result = collection.findOneAndUpdate(filter, update);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": {
      "_id": "101"
    },
    "update": {
        "$set": {
            "color": "blue",
            "address.city": "Austin",
            "classes.2": "biology"
            }
    }
  }
}'

Insert a new document if no matching document exists

You can use upsert to insert a new document if no document matches the filter criteria.

  • 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 a document
result = collection.find_one_and_update(
    {
        "$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 a document
result = collection.find_one_and_update(
    {
        "$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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    {
      $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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {
      $set: {color: "blue"},
      $setOnInsert: {
        "customer.name": "James"
      }
    },
    { upsert: true },
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneAndUpdateOptions;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;

import java.util.Optional;

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Update update = Updates.set("color", "blue");
        CollectionFindOneAndUpdateOptions options = new CollectionFindOneAndUpdateOptions().upsert(true);
        Optional<Document> result = collection.findOneAndUpdate(filter, update, options);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "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 '{
  "findOneAndUpdate": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "update": {
      "$set": { "color": "blue" },
      "$setOnInsert": {
        "customer.name": "James"
      }
    },
    "options": { "upsert": true }
  }
}'

Include the updated values in the response

By default, the response reflects the document before the update. You can specify that you want the response to use the updated values instead.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient
from astrapy.constants import ReturnDocument

# 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 a document
result = collection.find_one_and_update(
    {"_id": "101"},
    {"$set": {"color": "blue"}},
    return_document=ReturnDocument.AFTER
)

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 a document
(async function () {
  const result = await collection.findOneAndUpdate(
    { _id: "101" },
    {$set: {color: "blue"}},
    {returnDocument: 'after'}
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneAndUpdateOptions;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;

import java.util.Optional;

public class FindOneAndUpdate {

    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 a document
        Filter filter = Filters.eq("_id", "101");
        Update update = Updates.set("color", "blue");
        CollectionFindOneAndUpdateOptions options = new CollectionFindOneAndUpdateOptions().returnDocumentAfter();
        Optional<Document> result = collection.findOneAndUpdate(filter, update, options);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": {
      "_id": "101"
    },
    "update": { "$set": { "color": "blue" } },
    "options": { "returnDocument": "after" }
  }
}'

Include only specific fields in the response

To specify which fields to include or exclude in the returned document, use a projection.

Certain fields, like $vector and $vectorize, are excluded by default and will only be returned if you specify them in the projection. Certain fields, like _id, are included by default.

  • 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")

# Find a document
result = collection.find_one_and_update(
    {"metadata.language": "English"},
    {"$set": {"color": "blue"}},
    projection={"isCheckedOut": True, "title": 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');

// Find a document
(async function () {
  const result = await collection.findOneAndUpdate(
    { "metadata.language": "English" },
    {$set: {color: "blue"}},
    { projection: { isCheckedOut: true, title: true} },
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneAndUpdateOptions;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;
import com.datastax.astra.client.core.query.Projection;

import java.util.Optional;

public class FindOneAndUpdate {

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

        // Find a document
        Filter filter = Filters.eq("metadata.language", "English");
        Update update = Updates.set("color", "blue");
        CollectionFindOneAndUpdateOptions options = new CollectionFindOneAndUpdateOptions()
            .projection(Projection.include("isCheckedOut", "title"));
        Optional<Document> result = collection.findOneAndUpdate(filter, update, options);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": {"metadata.language": "English"},
    "update": { "$set": { "color": "blue" } },
    "projection": {"isCheckedOut": true, "title": true}
  }
}'

Exclude specific fields from the response

To specify which fields to include or exclude in the returned document, use a projection.

Certain fields, like $vector and $vectorize, are excluded by default and will only be returned if you specify them in the projection. Certain fields, like _id, are included by default.

  • 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")

# Find a document
result = collection.find_one_and_update(
    {"metadata.language": "English"},
    {"$set": {"color": "blue"}},
    projection={"isCheckedOut": False, "title": False}
)

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

// Find a document
(async function () {
  const result = await collection.findOneAndUpdate(
    { "metadata.language": "English" },
    {$set: {color: "blue"}},
    { projection: { isCheckedOut: false, title: false} },
  );

  console.log(result);
})();
package com.examples;

import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneAndUpdateOptions;
import com.datastax.astra.client.collections.commands.Update;
import com.datastax.astra.client.collections.commands.Updates;
import com.datastax.astra.client.core.query.Projection;

import java.util.Optional;

public class FindOneAndUpdate {

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

        // Find a document
        Filter filter = Filters.eq("metadata.language", "English");
        Update update = Updates.set("color", "blue");
        CollectionFindOneAndUpdateOptions options = new CollectionFindOneAndUpdateOptions()
            .projection(Projection.exclude("isCheckedOut", "title"));
        Optional<Document> result = collection.findOneAndUpdate(filter, update, options);
        System.out.println(result);
    }
}
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 '{
  "findOneAndUpdate": {
    "filter": {"metadata.language": "English"},
    "update": { "$set": { "color": "blue" } },
    "projection": {"isCheckedOut": false, "title": false}
  }
}'

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