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 find and replace a document have the same database effect but differ in their return value. This method returns details about the success of the operation. The method to find and replace a document returns the document that was found and replaced.

Method signature

  • Python

  • TypeScript

  • Java

  • curl

collection.replace_one(
    filter: Dict[str, Any],
    replacement: Dict[str, Any],
    *,
    sort: Dict[str, Any],
    upsert: bool,
    max_time_ms: int,
) -> UpdateResult
collection.replaceOne(
  filter: Filter<Schema>,
  replacement: NoId<Schema>,
  options?: {
    upsert?: boolean,
    sort?: Sort,
    maxTimeMS?: number,
  },
): Promise<ReplaceOneResult<Schema>>
UpdateResult replaceOne(
  Filter filter,
  T replacement
)
UpdateResult replaceOne(
  Filter filter,
  T replacement,
  ReplaceOneOptions options
)

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

Result

  • Python

  • TypeScript

  • Java

  • curl

Replaces a document that matches the specified parameters, and returns an UpdateResult object that includes details about the success of the operation.

Example response:

UpdateResult(update_info={'n': 1, 'updatedExisting': True, 'ok': 1.0, 'nModified': 1}, raw_results=...)

Example response if a new document was inserted:

UpdateResult(update_info={'n': 1, 'updatedExisting': False, 'ok': 1.0, 'nModified': 0, 'upserted': '21562817-2ee9-4585-9628-172ee9a5853e'}, raw_results=...)

Replaces a document that matches the specified parameters, and returns a promise that resolves to a ReplaceOneResult<Schema> object that includes details about the success of the operation.

Example resolved response:

{ modifiedCount: 1, matchedCount: 1, upsertedCount: 0 }

Example resolved response if a new document was inserted:

{
  modifiedCount: 0,
  matchedCount: 0,
  upsertedId: '837b054d-4a8b-4458-bb05-4d4a8b0458b7',
  upsertedCount: 1
}

Replaces a document that matches the specified parameters and returns UpdateResults<T>, which includes details about the success of the operation.

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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]

An object describing the document to insert.

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

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

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

ReplaceOneOptions

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

Properties of options
Name Type Summary

upsert

boolean

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

Default: False

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.

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

ReplaceOneOptions

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

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

upsert()

boolean

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

Default: False

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {"_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.replaceOne(
    { _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 com.datastax.astra.client.model.UpdateResult;

public class ReplaceOne {

    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);
        UpdateResult result = collection.replaceOne(filter, newDocument);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {
        "$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.replaceOne(
    {
      $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 com.datastax.astra.client.model.UpdateResult;

public class ReplaceOne {

    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");
        UpdateResult result = collection.replaceOne(filter, newDocument);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {},
    {
      "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.replaceOne(
    {},
    {
      name: "John Doe",
      age: 42
    },
    { sort: { $vector: [0.1, 0.2, 0.3] } },
  );

  console.log(result);
})();

The Java client does not support vector search with replaceOne. Instead, you can use findOne to find the _id of a document with vector search, and then use replaceOne and the document’s _id to replace the document. Or, you can use findOneAndReplace.

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {},
    {
      "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.replaceOne(
    {},
    {
      name: "John Doe",
      age: 42
    },
    { sort: { $vectorize: "Text to vectorize" } }
  );

  console.log(result);
})();

The Java client does not support vector search with replaceOne. Instead, you can use findOne to find the _id of a document with vector search, and then use replaceOne and the document’s _id to replace the document. Or, you can use findOneAndReplace.

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {"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.replaceOne(
    { "metadata.language": "English" },
    {
      isCheckedOut: false,
      numberOfPages: 400
    },
    { sort: {
      rating: 1, // ascending
      title: -1 // descending
    } }
  );

  console.log(result);
})();

The Java client does not support vector search with replaceOne. Instead, you can use findOne to find the _id of a document with vector search, and then use replaceOne and the document’s _id to replace the document. Or, you can use findOneAndReplace.

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {"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.replaceOne(
    { "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 com.datastax.astra.client.model.UpdateResult;

public class ReplaceOne {

    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"
            ));
        UpdateResult result = collection.replaceOne(filter, newDocument);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {"_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.replaceOne(
    { _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 com.datastax.astra.client.model.UpdateResult;

public class ReplaceOne {

    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});
        UpdateResult result = collection.replaceOne(filter, newDocument);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {"_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.replaceOne(
    { _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 com.datastax.astra.client.model.UpdateResult;

public class ReplaceOne {

    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");
        UpdateResult result = collection.replaceOne(filter, newDocument);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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.replace_one(
    {
        "$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.replaceOne(
    {
      $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.ReplaceOneOptions;
import com.datastax.astra.client.model.UpdateResult;

public class ReplaceOne {

    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");
        ReplaceOneOptions options = new ReplaceOneOptions().upsert(true);
        UpdateResult result = collection.replaceOne(filter, newDocument, options);
        System.out.println(result.getMatchedCount());
        System.out.println(result.getModifiedCount());
    }
}

This method has no literal equivalent in HTTP. Instead, you can use Find and replace a document with "projection": {"*": false}, which excludes all document fields from the response.

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