Insert a document (TypeScript)
Inserts a single document into a collection.
Documents are stored in collections. They represent a single row or record of data in Hyper-Converged Database (HCD) databases. For more information, see About collections with the Data API (TypeScript).
If the collection is vector-enabled, pregenerated vector embeddings can be included by using the reserved $vector field.
You can later use the $vector field to perform a vector search.
If the collection has lexical enabled, use the reserved $lexical field to store a string to index for lexicographical matching.
|
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
Inserts the specified document and returns a promise that resolves to a CollectionInsertOneResult<Schema> object that includes the ID of the inserted document.
The ID value depends on the ID type. For more information, see Document IDs (TypeScript).
Example response:
{ insertedId: '92b3c4f4-db44-4440-b4c4-f4db54e440b8' }
Parameters
Use the insertOne method, which belongs to the Collection class.
Method signature
async insertOne(
document: MaybeId<Schema>,
options?: {
timeout?: number | TimeoutDescriptor,
},
): CollectionInsertOneResult<Schema>
| Name | Type | Summary |
|---|---|---|
|
An object describing the document to insert. A document can contain user-defined and reserved fields. User-defined field names can be any non-empty sequence of Unicode characters, with the following exceptions:
Reserved fields are tied to specific functionality. Include the following reserved fields in your documents, if applicable:
For examples, see Examples. |
|
|
Optional.
The options for this operation. See Properties of |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. The timeout(s) to apply to this method.
You can specify For more information about the |
Examples
The following examples demonstrate how to insert a document into a collection.
Insert a 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");
// Insert a document into the collection
(async function () {
const result = await collection.insertOne({
title: "Hidden Shadows of the Past",
genres: ["Biography", "Graphic Novel", "Dystopian", "Drama"],
metadata: {
isbn: "978-1-905585-40-3",
language: "French",
edition: "Anniversary Edition",
},
number_of_pages: 245,
});
})();
Insert a document with vector embeddings
Use the reserved $vector field to insert a document with pregenerated vector embeddings.
You can later use this field to perform a vector search.
All embeddings in the collection should use the same provider, model, and dimensions. Mismatched embeddings can cause inaccurate vector searches.
The $vector field is only supported 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");
// Insert a document into the collection
(async function () {
const result = await collection.insertOne({
name: "Jane Doe",
$vector: [0.08, -0.62, 0.39],
});
})();
Insert a document for retrieval with lexicographical matching
|
Lexicographical matching is currently in public preview. Development is ongoing, and the features and functionality are subject to change. Hyper-Converged Database (HCD), and the use of such, is subject to the DataStax Preview Terms. |
If you plan to use lexicographical matching to find this document, the document must have the $lexical field populated.
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");
// Insert a document into the collection
(async function () {
const result = await collection.insertOne({
name: "Jane Doe",
$lexical: "An active hiker, runner, and triathlete who loves the outdoors.",
});
})();
Insert a document and specify the ID
The TypeScript client provides the UUID and ObjectId classes to use and generate identifiers.
These are not the same as those exported from the uuid or bson libraries.
To generate new identifiers, you can use UUID.v1(), UUID.v4(), UUID.v6(), UUID.v7(), or new ObjectId().
UUIDs can also be constructed from a string representation of the IDs.
You can also use the uuid and oid shorthand methods.
You can also directly specify a value.
All UUID methods return an instance of the same class, which exposes a version property.
Example using new UUID.v7():
import {
DataAPIClient,
UUID,
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");
// Insert a document into the collection
(async function () {
const result = await collection.insertOne({
_id: UUID.v7(),
name: "Jane Doe",
});
})();
Example using new ObjectId() with input:
import {
DataAPIClient,
ObjectId,
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");
// Insert a document into the collection
(async function () {
const result = await collection.insertOne({
_id: new ObjectId("6672e1cbd7fabb4e5493916f"),
name: "Jane Doe",
});
})();
Example specifying the ID without UUID or ObjectId:
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");
// Insert a document into the collection
(async function () {
const result = await collection.insertOne({
_id: 1,
name: "Jane Doe",
});
})();
Insert a document with a binary field
You can insert binary data as a Base64-encoded string with $binary.
You can also also use the CollectionCodecs class to write a custom code.
CollectionCodecs is currently in beta.
The DataAPIBlob class is not supported by default for collections.
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");
// Insert a document with a binary field
(async function () {
const result = await collection.insertOne({
exampleBinary: { $binary: "PfvnbT7peNU/Sfvn" },
});
})();
Insert a document with nested fields
Although you can use dot notation in a filter to find a document, you cannot use dot notation to insert a document. To specify nested fields in the inserted document, you must build a map, list, or set.
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");
// Insert a document into the collection
(async function () {
const result = await collection.insertOne({
title: "Hidden Shadows of the Past",
genres: ["Biography", "Graphic Novel", "Dystopian", "Drama"],
metadata: {
isbn: "978-1-905585-40-3",
language: "French",
edition: "Anniversary Edition",
},
});
})();
Client reference
For more information, see the client reference.