Find and update a document (TypeScript)
Finds a single document in a collection using filter and sort clauses, and then updates properties in that document. Optionally, if no document matches the filter, inserts a new document.
This method and the method to update a document have the same database effect but differ in their return value. This method returns the document that was found and updated. The method to update a document returns details about the success of the update.
|
Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart. |
Result
Updates a document that matches the specified parameters, and returns a promise that resolves to the document.
If no document was found, returns returns a promise that resolves to null.
The method parameters control whether the returned document reflects the original or updated values.
The fields included in the returned document depend on the projection specified in the method.
If an upsert is requested, the method inserts a new document if no document matches the filter.
Example resolved response:
{_id: 101, name: 'John Doe'}
Parameters
Use the findOneAndUpdate method, which belongs to the Collection class.
Method signature
async findOneAndUpdate(
filter: CollectionFilter<Schema>,
update: CollectionUpdateFilter<Schema>,
options?: {
returnDocument?: 'before' | 'after',
upsert?: boolean,
sort?: Sort,
projection?: Projection,
includeResultMetadata?: boolean,
timeout?: number | TimeoutDescriptor,
},
): Schema | null
| Name | Type | Summary |
|---|---|---|
|
An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria. Filters can improve performance by reducing the number of documents that the Data API processes. You must use For a list of available filter operators and more examples, see Filter operators for collections (TypeScript). Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter. For an example, see Update a document that matches a filter. |
|
|
An object that defines the updates using Data API operators. For a list of available operators and more examples, see Update operators for collections (TypeScript). You must use |
|
|
Optional.
The options for this operation. See Properties of |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. Controls whether the response reflects the document before or after the update. Can be one of:
For an example, see Include the updated values in the response. Default: |
|
|
Optional. Whether to insert a new document if no document matches the filter criteria. For an example, see Insert a new document if no matching document exists. Default: False |
|
Optional. Controls which fields are included or excluded in the returned document. You must use For more information, see Projections for collections (TypeScript). Default: The default projection for the collection.
All fields prefixed with For examples, see Include only specific fields in the response and Exclude specific fields from the response. |
|
|
Optional. Sorts documents by one or more fields, or performs a vector search. You must use For more information, see Sort clauses for collections (TypeScript). Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries. For vector searches, this parameter can use |
|
|
|
Whether to include details about the operation in the response. Default: False |
|
|
Optional. The timeout(s) to apply to this method.
You can specify For more information about the |
Examples
The following examples demonstrate how to update a document in a collection.
Update a document by ID
All documents have a unique _id property. You can use a filter to find a document with a specific _id, and then update that document.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{ _id: "101" },
{ $set: { color: "blue" } },
);
console.log(result);
})();
Update a document that matches a filter
You can use a filter to find a document that matches specific criteria.
For example, you can find a document with an is_checked_out value of false and a number_of_pages value less than 300.
For a list of available filter operators and more examples, see Filter operators for collections (TypeScript).
Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{
$and: [{ is_checked_out: false }, { number_of_pages: { $lt: 300 } }],
},
{ $set: { color: "blue" } },
);
console.log(result);
})();
Update a document that is most similar to a search vector
To find the document whose $vector value is most similar to a given vector, use a sort with the vector embeddings that you want to match. For more information, see Find data with vector search.
Vector search is only available for vector-enabled collections.
For more information, see Create a collection that can store vector embeddings and $vector in collections (TypeScript).
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{},
{ $set: { color: "blue" } },
{ sort: { $vector: [0.08, -0.62, 0.39] } },
);
console.log(result);
})();
Update a document after applying a non-vector sort
You can use a sort clause to sort documents by one or more fields.
For more information, see Sort clauses for collections (TypeScript).
Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Find a document
(async function () {
const result = await collection.findOneAndUpdate(
{ "metadata.language": "English" },
{ $set: { color: "blue" } },
{
sort: {
rating: 1, // ascending
title: -1, // descending
},
},
);
console.log(result);
})();
Update multiple properties
You can combine multiple operators and properties in a single request. For the full list of operators, see Update operators for collections (TypeScript).
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{ _id: "101" },
{
$set: {
color: "blue",
classes: ["biology", "algebra", "swimming"],
},
$unset: {
phone: "",
},
$inc: {
age: 1,
},
},
);
console.log(result);
})();
Update nested properties
To update a nested property, use dot notation.
For example, field.subfield.subsubfield.
To update an item in a list, specify a numeric index.
For example, listProperty.3.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{ _id: "101" },
{
$set: {
color: "blue",
"address.city": "Austin",
"classes.2": "biology",
},
},
);
console.log(result);
})();
Insert a new document if no matching document exists
You can use upsert to insert a new document if no document matches the filter criteria.
In addition to any fields you explicitly set in the update parameter, the new document also includes any top-level equality conditions from the filter parameter.
Equality conditions that are nested within $and from the filter parameter are not included.
If a field is defined both in the filter and in the update, the explicitly set value takes precedence.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{
$and: [{ is_checked_out: false }, { number_of_pages: { $lt: 300 } }],
},
{ $set: { color: "blue" } },
{ upsert: true },
);
console.log(result);
})();
You can also use the setOnInsert operator to specify additional fields to set if a new document is created:
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{
$and: [{ is_checked_out: false }, { number_of_pages: { $lt: 300 } }],
},
{
$set: { color: "blue" },
$setOnInsert: {
"customer.name": "James",
},
},
{ upsert: true },
);
console.log(result);
})();
Include the updated values in the response
By default, the response reflects the document before the update. You can specify that you want the response to use the updated values instead.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Update a document
(async function () {
const result = await collection.findOneAndUpdate(
{ _id: "101" },
{ $set: { color: "blue" } },
{ returnDocument: "after" },
);
console.log(result);
})();
Include only specific fields in the response
To specify which fields to include or exclude in the returned document, use a projection.
All fields prefixed with $ are excluded by default and will only be returned if you include them in the projection.
_id is included by default and will always be returned unless you exclude it from the projection.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Find a document
(async function () {
const result = await collection.findOneAndUpdate(
{ "metadata.language": "English" },
{ $set: { color: "blue" } },
{ projection: { is_checked_out: true, title: true } },
);
console.log(result);
})();
Exclude specific fields from the response
To specify which fields to include or exclude in the returned document, use a projection.
All fields prefixed with $ are excluded by default and will only be returned if you include them in the projection.
_id is included by default and will always be returned unless you exclude it from the projection.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Find a document
(async function () {
const result = await collection.findOneAndUpdate(
{ "metadata.language": "English" },
{ $set: { color: "blue" } },
{ projection: { is_checked_out: false, title: false } },
);
console.log(result);
})();
Work with . and & in field names
You must use & to escape any . or & in field names when the field is used in a filter, sort, projection, update, or indexing clause.
Dot notation, which is used to reference nested fields, should not be escaped.
For more information, see Work with . and & in field names (TypeScript).
For example, in the following document, you would use escaping like this: areas.r&&d, costs.price&.usd, and costs.price&.cad.
{
"areas": {
"r&d": true,
"design": false
},
"costs": {
"price.usd": 100,
"price.cad": 90
}
}
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Find a document
(async function () {
const result = await collection.findOneAndUpdate(
{
$and: [{ "areas.r&&d": false }, { "costs.price&.usd": { $lt: 300 } }],
},
{
$set: {
"areas.r&&d": true,
"costs.price&.usd": 310,
},
},
);
console.log(result);
})();
You can also use the escapeFieldNames function provided by the client:
import {
DataAPIClient,
UsernamePasswordTokenProvider,
escapeFieldNames,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");
// Find a document
(async function () {
const result = await collection.findOneAndUpdate(
{
$and: [
{ [escapeFieldNames("areas", "r&d")]: false },
{ [escapeFieldNames("costs", "price.usd")]: { $lt: 300 } },
],
},
{
$set: {
[escapeFieldNames("areas", "r&d")]: true,
[escapeFieldNames("costs", "price.usd")]: 310,
},
},
);
console.log(result);
})();
Client reference
For more information, see the client reference.