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.
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 | ||
---|---|---|---|---|
|
|
A predicate expressed as a dictionary according to the Data API filter syntax.
For example: |
||
|
|
The new document to write into the collection.
Define all fields that the replacement document must include, except for the
|
||
|
|
See Find a document and Sort clauses. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries. |
||
|
|
This parameter controls the behavior if there are no matches.
If true and there are no matches, then the operation inserts the |
||
|
|
A timeout, in milliseconds, for the underlying HTTP request. This method uses the collection-level timeout by default. |
Name | Type | Summary | ||
---|---|---|---|---|
|
A filter to select the document to replace. For a list of available operators and examples, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries. |
|||
|
The new document to write into the collection.
Define all fields that the replacement document must include, except for the
|
|||
|
The options for this operation. |
Options (ReplaceOneOptions
):
Name | Type | Summary |
---|---|---|
|
This parameter controls the behavior if there are no matches.
If true and there are no matches, then the operation inserts the |
|
See Find a document and Sort clauses. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries. |
||
|
The maximum time in milliseconds that the client should wait for the operation to complete each underlying HTTP request. |
Name | Type | Summary | ||
---|---|---|---|---|
|
|
Filter criteria to find the document to replace. The filter is a JSON object that can contain any valid Data API filter expression. For a list of available operators and examples, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries. |
||
|
|
The new document to write into the collection.
Define all fields that the replacement document must include, except for the
|
||
|
Set the different options for the
|
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, constants
# 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": constants.SortDocuments.ASCENDING,
"title": constants.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.