Find and replace a document

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

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

Method signature

  • Python

  • TypeScript

  • Java

  • curl

The following method belongs to the astrapy.Collection class.

find_one_and_replace(
  filter: Dict[str, Any],
  replacement: Dict[str, Any],
  *,
  projection: Iterable[str] | Dict[str, bool],
  sort: Dict[str, Any],
  upsert: bool,
  return_document: str,
  max_time_ms: int,
) -> Dict[str, Any]

The following method belongs to the Collection class.

async findOneAndReplace(
  filter: Filter<Schema>,
  replacement: NoId<Schema>,
  options?: {
    returnDocument?: 'before' | 'after',
    upsert?: boolean,
    sort?: Sort,
    projection?: Projection,
    includeResultMetadata?: boolean,
    maxTimeMS?: number,
  },
): ModifyResult<Schema>

The following methods belong to the com.datastax.astra.client.Collection class.

Optional<T> findOneAndReplace(
  Filter filter,
  T replacement
)
Optional<T> findOneAndReplace(
  Filter filter,
  T replacement,
  FindOneAndReplaceOptions options
)
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 '{
  "findOneAndReplace": {
    "filter": FILTER,
    "replacement": REPLACEMENT,
    "sort": SORT,
    "projection": PROJECTION,
    "options": {
      "upsert": BOOLEAN,
      "returnDocument": RETURN_DOCUMENT_DIRECTIVE
    }
  }
}'

Result

  • Python

  • TypeScript

  • Java

  • curl

Replaces 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'}

Replaces a document that matches the specified parameters, and returns a promise that resolves to the document (WithId<Schema>). 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'}

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

Replaces 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

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 the filter criteria.

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

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

replacement

Dict[str, Any]

A dictionary describing the document to insert.

The replacement document should not include _id. The _id of the replaced document will be retained.

projection

Iterable[str] | Dict[str, bool]

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

For more information, see Projection operations.

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.

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.

upsert

bool

Optional. Whether a new document should be inserted if no document matches the filter criteria.

Default: False

return_document

str

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

Can be one of:

Default: "before"

max_time_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 object.

Name Type Summary

filter

Filter<Schema>

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

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

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

replacement

NoId<Schema>

An object describing the document to insert.

The replacement document should not include _id. The _id of the replaced document will be retained.

options

FindOneAndReplaceOptions

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

Can be one of:

  • "before"

  • "after"

Default: "before"

upsert

boolean

Optional. Whether a new document should be inserted 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 Projection operations.

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.

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.

maxTimeMS

number

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

includeResultMetadata

boolean

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

Default: False

Name Type Summary

filter

Filter

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

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

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

replacement

T

An object describing the document to insert.

The replacement document should not include _id. The _id of the replaced document will be retained.

options

FindOneAndReplaceOptions

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

Methods of the FindOneAndReplaceOptions 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.

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

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 a new document should be inserted if no document matches the filter criteria.

Default: False

returnDocumentAfter()

None

Optional. The response reflects the document after the replacement.

returnDocumentBefore()

None

Optional. The response reflects the document before the replacement.

This is the default unless returnDocumentAfter() is used.

Use the findOneAndReplace command with these parameters:

Name Type Summary

filter

object

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

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

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

sort

object

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

For more information, see Sort clauses.

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.

replacement

object

A JSON object describing the document to insert.

The replacement document should not include _id. The _id of the replaced document will be retained.

projection

object

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

For more information, see Projection operations.

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 a new document should be inserted 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 replace a document in a collection.

Replace 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 replace 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")

# Replace a document
result = collection.find_one_and_replace(
    {"_id": "101"},
    {
      "name": "John Doe",
      "age": 42
    }
)

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

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    { _id: "101" },
    {
      name: "John Doe",
      age: 42
    }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.eq("_id", "101");
        Document newDocument = new Document()
            .append("name", "John Doe")
            .append("age", 42);
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument);
        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 '{
  "findOneAndReplace": {
    "filter": {
      "_id": "101"
    },
    "replacement": {
      "name": "John Doe",
      "age": 42
    }
  }
}'

Replace 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 Data API operators.

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

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

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

# Replace a document
result = collection.find_one_and_replace(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    {
      "isCheckedOut": True,
      "borrower": "Brook Reed"
    }
)

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

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {
      isCheckedOut: true,
      borrower: "Brook Reed"
    }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Document newDocument = new Document()
            .append("isCheckedOut", false)
            .append("borrower", "Brook Reed");
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument);
        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 '{
  "findOneAndReplace": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "replacement": {
      "isCheckedOut": true,
      "borrower": "Brook Reed"
    }
  }
}'

Replace 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 Perform a vector search.

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

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

# Replace a document
result = collection.find_one_and_replace(
    {},
    {
      "name": "John Doe",
      "age": 42
    },
    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');

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    {},
    {
      name: "John Doe",
      age: 42
    },
    { sort: { $vector: [0.1, 0.2, 0.3] } },
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneAndReplaceOptions;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Document newDocument = new Document()
            .append("name", "John Doe")
            .append("age", 42);
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions()
            .sort(new float[] {0.12f, 0.52f, 0.32f});
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument, 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 '{
  "findOneAndReplace": {
    "sort": {
      "$vector": [0.1, 0.2, 0.3]
    },
    "replacement": {
      "name": "John Doe",
      "age": 42
    }
  }
}'

Replace 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 Perform a vector search.

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

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

# Replace a document
result = collection.find_one_and_replace(
    {},
    {
      "name": "John Doe",
      "age": 42
    },
    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');

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    {},
    {
      name: "John Doe",
      age: 42
    },
    { sort: { $vectorize: "Text to vectorize" } }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneAndReplaceOptions;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Document newDocument = new Document()
            .append("name", "John Doe")
            .append("age", 42);
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions()
            .sort("Text to vectorize");
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument, 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 '{
  "findOneAndReplace": {
    "sort": { "$vectorize": "Text to vectorize" },
    "replacement": {
      "name": "John Doe",
      "age": 42
    }
  }
}'

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

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 SortDocuments

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

# Replace a document
result = collection.find_one_and_replace(
    {"metadata.language": "English"},
    {
      "isCheckedOut": False,
      "numberOfPages": 400
    },
    sort={
        "rating": SortDocuments.ASCENDING,
        "title": SortDocuments.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');

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    { "metadata.language": "English" },
    {
      isCheckedOut: false,
      numberOfPages: 400
    },
    { sort: {
      rating: 1, // ascending
      title: -1 // descending
    } }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneAndReplaceOptions;
import com.datastax.astra.client.model.Sorts;

import java.util.Optional;

public class FindOneAndReplace {

    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");
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions()
            .sort(Sorts.ascending("rating"))
            .sort(Sorts.descending("title"));
        Document newDocument = new Document()
            .append("isCheckedOut", false)
            .append("numberOfPages", 400);
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument, 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 '{
  "findOneAndReplace": {
    "filter": { "metadata.language": "English" },
    "replacement": {
      "isCheckedOut": false,
      "numberOfPages": 400
    },
    "sort": {
      "rating": 1,
      "title": -1
    }
  }
}'

Use nested fields in the replacement document

Although you can use dot notation in the filter to find a document, you can’t use dot notation in the replacement document. To specify nested fields in the replacement document, you must build a map, list, or set.

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

# Replace a document
result = collection.find_one_and_replace(
    {"metadata.language": "English"},
    {
        "title": "Hidden Shadows of the Past",
        "numberOfPages": 481,
        "genres": ["Biography", "Graphic Novel", "Dystopian", "Drama"],
        "metadata": {
            "ISBN": "978-1-905585-40-3",
            "language": "French",
            "edition": "Anniversary Edition"
          },
    }
)

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

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    { "metadata.language": "English" },
    {
      title: "Hidden Shadows of the Past",
      numberOfPages: 481,
      genres: ["Biography", "Graphic Novel", "Dystopian", "Drama"],
      metadata: {
        ISBN: "978-1-905585-40-3",
        language: "French",
        edition: "Anniversary Edition"
      },
    }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.eq("metadata.language", "English");
        Document newDocument = new Document()
            .append("title", "Hidden Shadows of the Past")
            .append("numberOfPages", 481)
            .append("genres", Set.of("Biography", "Graphic Novel", "Dystopian", "Drama"))
            .append("metadata", Map.of(
                "ISBN", "978-1-905585-40-3",
                "language", "French",
                "edition", "Anniversary Edition"
            ));
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument);
        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 '{
  "findOneAndReplace": {
    "filter": {"metadata.language": "English"},
    "replacement": {
      "title": "Hidden Shadows of the Past",
      "numberOfPages": 481,
      "genres": ["Biography", "Graphic Novel", "Dystopian", "Drama"],
      "metadata": {
        "ISBN": "978-1-905585-40-3",
        "language": "French",
        "edition": "Anniversary Edition"
      }
    }
  }
}'

Use vector embeddings in the replacement document

Use the reserved $vector field to insert a document with pregenerated vector embeddings.

Only vector-enabled collections support the $vector field. For more information, see Vector and vectorize.

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

# Replace a document
result = collection.find_one_and_replace(
    {"_id": "101"},
    {
      "name": "Jane Doe",
      "$vector": [.08, .68, .30],
    },
)

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

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    { _id: "101" },
    {
      name: 'Jane Doe',
      $vector: [.08, .68, .30],
    }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.eq("_id", "101");
        Document newDocument = new Document()
            .append("name", "John Doe")
            .vector(new float[] {0.12f, 0.52f, 0.32f});
        Optional<Document> result result = collection.findOneAndReplace(filter, newDocument);
        System.out.println(result);
    }
}
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 '{
  "findOneAndReplace": {
    "filter": {
      "_id": "101"
    },
    "replacement": {
      "name": "John Doe",
      "$vector": [.08, .68, .30]
    }
  }
}'

Use vectorize to generate vector embeddings in the replacement document

Use the reserved $vectorize field to generate a vector embedding automatically. The value of $vectorize can be any string.

Only collections that have vectorize enabled support the $vectorize field. For more information, see Vector and vectorize and Auto-generate embeddings with vectorize.

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

# Replace a document
result = collection.find_one_and_replace(
    {"_id": "101"},
    {
      "name": "Jane Doe",
      "$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');

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    { _id: "101" },
    {
      name: 'Jane Doe',
      $vectorize: 'Text to vectorize',
    }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.eq("_id", "101");
        Document newDocument = new Document()
            .append("name", "Jane Doe")
            .append("$vectorize", "Text to vectorize");
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument);
        System.out.println(result);
    }
}
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 '{
  "findOneAndReplace": {
    "filter": {
      "_id": "101"
    },
    "replacement": {
      "name": "Jane Doe",
      "$vectorize": "Text to vectorize"
    }
  }
}'

Insert a new document if no matching document exists

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

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

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

# Replace a document
result = collection.find_one_and_replace(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    {
      "isCheckedOut": True,
      "borrower": "Brook Reed"
    },
    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');

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    {
      $and: [
        { isCheckedOut: false },
        { numberOfPages: { $lt: 300 } }
      ],
    },
    {
      isCheckedOut: true,
      borrower: "Brook Reed"
    },
    { upsert: true },
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneAndReplaceOptions;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        Document newDocument = new Document()
            .append("isCheckedOut", false)
            .append("borrower", "Brook Reed");
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions().upsert(true);
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument, 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 '{
  "findOneAndReplace": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "replacement": {
      "isCheckedOut": true,
      "borrower": "Brook Reed"
    },
    "options": { "upsert": true }
  }
}'

Include the new document in the response

By default, the response will reflect the document before the replacement. You can specify that you want the response to use the replacement document 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")

# Replace a document
result = collection.find_one_and_replace(
    {"_id": "101"},
    {
      "isCheckedOut": True,
      "borrower": "Brook Reed"
    },
    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');

// Replace a document
(async function () {
  const result = await collection.findOneAndReplace(
    { _id: "101" },
    {
      isCheckedOut: true,
      borrower: "Brook Reed"
    },
    {returnDocument: 'after'}
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneAndReplaceOptions;

import java.util.Optional;

public class FindOneAndReplace {

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

        // Replace a document
        Filter filter = Filters.eq("_id", "101");
        Document newDocument = new Document()
            .append("isCheckedOut", false)
            .append("borrower", "Brook Reed");
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions().returnDocumentAfter();
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument, 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 '{
  "findOneAndReplace": {
    "filter": {
      "_id": "101"
    },
    "replacement": {
      "isCheckedOut": true,
      "borrower": "Brook Reed"
    },
    "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 that they should be included. 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_replace(
    {"metadata.language": "English"},
    {
      "isCheckedOut": True,
      "borrower": "Brook Reed"
    },
    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.findOneAndReplace(
    { "metadata.language": "English" },
    {
      isCheckedOut: true,
      borrower: "Brook Reed"
    },
    { projection: { isCheckedOut: true, title: true} },
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneAndReplaceOptions;
import com.datastax.astra.client.model.Projections;

import java.util.Optional;

public class FindOneAndReplace {

    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");
        Document newDocument = new Document()
            .append("isCheckedOut", false)
            .append("borrower", "Brook Reed");
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions()
            .projection(Projections.include("isCheckedOut", "title"));
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument, 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 '{
  "findOneAndReplace": {
    "filter": {"metadata.language": "English"},
    "replacement": {
      "isCheckedOut": true,
      "borrower": "Brook Reed"
    },
    "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 that they should be included. 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_replace(
    {"metadata.language": "English"},
    {
      "isCheckedOut": True,
      "borrower": "Brook Reed"
    },
    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.findOneAndReplace(
    { "metadata.language": "English" },
    {
      isCheckedOut: true,
      borrower: "Brook Reed"
    },
    { projection: { isCheckedOut: false, title: false} },
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneAndReplaceOptions;
import com.datastax.astra.client.model.Projections;

import java.util.Optional;

public class FindOneAndReplace {

    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");
        Document newDocument = new Document()
            .append("isCheckedOut", false)
            .append("borrower", "Brook Reed");
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions()
            .projection(Projections.exclude("isCheckedOut", "title"));
        Optional<Document> result = collection.findOneAndReplace(filter, newDocument, 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 '{
  "findOneAndReplace": {
    "filter": {"metadata.language": "English"},
    "replacement": {
      "isCheckedOut": true,
      "borrower": "Brook Reed"
    },
    "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