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.
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 | ||
---|---|---|---|---|
|
|
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 Projection clauses. |
||
|
|
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 flag controlling what document is returned.
If set to |
||
|
|
A timeout, in milliseconds, for the underlying HTTP request. This method uses the collection-level timeout by default. |
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 (FindOneAndReplaceOptions
):
Name | Type | Summary |
---|---|---|
|
Specifies whether to return the original ( |
|
|
This parameter controls the behavior if there are no matches.
If true and there are no matches, then the operation inserts the |
|
See Find a document and Projection clauses. |
||
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. |
|
|
When true, returns |
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 find and replace operation, including the following:
|
Name | Type | Summary | ||
---|---|---|---|---|
|
|
The Data API command to find and replace one document in a collection based on |
||
|
|
Search criteria to find the document to replace.
For a list of available operators, see Data API operators.
For |
||
|
|
The new document to write into the collection.
Define all fields that the replacement document must include, except for the
|
||
|
|
Select a subset of fields to include in the response for the returned document. If empty or unset, the default projection is used. The default projection doesn’t always include all document fields. For more information and examples, see Projection clauses. |
||
|
|
This parameter controls the behavior if there are no matches.
If true and there are no matches, then the operation inserts the |
||
|
|
A flag controlling what document is returned.
If set to |
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, 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.find_one_and_replace(
{"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.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 com.datastax.astra.client.model.UpdateResult;
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});
UpdateResult result = collection.findOneAndReplace(filter, newDocument);
System.out.println(result.getMatchedCount());
System.out.println(result.getModifiedCount());
}
}
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
# 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=constants.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.