Insert documents (TypeScript)
Inserts multiple documents 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 for each document.
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 documents and returns a promise that resolves to a CollectionInsertManyResult<Schema> object that includes the IDs of the inserted documents and the number of inserted documents.
The ID value depends on the ID type. For more information, see Document IDs (TypeScript).
Example response:
{
insertedCount: 3,
insertedIds: [
'92b3c4f4-db44-4440-b4c4-f4db54e440b8',
101,
'132ffr343',
]
}
Parameters
Use the insertMany method, which belongs to the Collection class.
Method signature
async insertMany(
documents: MaybeId<Schema>[],
options?: {
ordered?: boolean,
concurrency?: number,
chunkSize?: number,
timeout?: number | TimeoutDescriptor,
},
): CollectionInsertManyResult<Schema>
| Name | Type | Summary |
|---|---|---|
|
An array of documents 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.
Whether the insertions must be processed sequentially.
If For an example, see Insert documents and specify insertion behavior. |
|
|
Optional. The maximum number of concurrent requests to the API at a given time. If For an example, see Insert documents and specify insertion behavior. Default: |
|
|
Optional. The number of documents to include in a single API request. DataStax recommends leaving this parameter unspecified to use the system default. For an example, see Insert documents and specify insertion behavior. Maximum: Default: |
|
|
|
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 multiple documents into a collection.
Insert documents
The documents can have different structures.
import {
DataAPIClient,
CollectionInsertManyError,
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 documents into the collection
(async function () {
try {
const result = await collection.insertMany([
{
name: "Jane Doe",
age: 42,
},
{
nickname: "Bobby",
color: "blue",
foods: ["carrots", "chocolate"],
},
]);
} catch (error) {
if (error instanceof CollectionInsertManyError) {
console.log(error.insertedIds());
}
}
})();
Insert documents with vector embeddings
Use the reserved $vector field to insert documents with pregenerated vector embeddings.
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).
You may also insert a mix of documents with and without the $vector field.
import {
DataAPIClient,
CollectionInsertManyError,
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 documents into the collection
(async function () {
try {
const result = await collection.insertMany([
{
name: "Jane Doe",
age: 42,
$vector: [0.08, -0.62, 0.39],
},
{
nickname: "Bobby",
$vector: [0.12, 0.53, 0.32],
},
]);
} catch (error) {
if (error instanceof CollectionInsertManyError) {
console.log(error.insertedIds());
}
}
})();
Insert documents 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 documents, each document must have the $lexical field populated.
import {
DataAPIClient,
CollectionInsertManyError,
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 documents into the collection
(async function () {
try {
const result = await collection.insertMany([
{
name: "Jane Doe",
$lexical: "An author who writes SciFi and fantasy novels.",
},
{
name: "Mary Day",
$lexical:
"An active hiker, runner, and triathlete who loves the outdoors.",
},
]);
} catch (error) {
if (error instanceof CollectionInsertManyError) {
console.log(error.insertedIds());
}
}
})();
Insert documents and specify the IDs
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(), or you can use the uuid and oid shorthand methods.
These methods accept a string representation of the IDs.
All UUID methods return an instance of the same class, which exposes a version property.
import {
DataAPIClient,
CollectionInsertManyError,
UUID,
ObjectId,
uuid,
oid,
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 documents into the collection
(async function () {
try {
const result = await collection.insertMany([
{
name: "Melissa",
_id: new ObjectId(),
},
{
name: "Jess",
_id: new ObjectId("65fd9b52d7fabba03349d013"),
},
{
name: "Adam",
_id: UUID.v4(),
},
{
name: "Beth",
_id: new UUID("016b1cac-14ce-660e-8974-026c927b9b91"),
},
{
name: "Cathy",
_id: uuid("bb3def0c-2ff2-43e1-b346-6cf0e5e36f10"),
},
{
name: "Debra",
_id: oid("67ea409a5e6499dabe0831bc"),
},
{
name: "Jane",
_id: 1,
},
{
name: "Bobby",
_id: "b_023",
},
]);
} catch (error) {
if (error instanceof CollectionInsertManyError) {
console.log(error.insertedIds());
}
}
})();
Insert documents and specify insertion behavior
import {
DataAPIClient,
CollectionInsertManyError,
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 documents into the collection
(async function () {
try {
const result = await collection.insertMany(
[
{
name: "Jane Doe",
age: 42,
},
{
nickname: "Bobby",
color: "blue",
foods: ["carrots", "chocolate"],
},
],
{
chunkSize: 2,
concurrency: 2,
ordered: false,
},
);
} catch (error) {
if (error instanceof CollectionInsertManyError) {
console.log(error.insertedIds());
}
}
})();
Insert documents 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.insertMany([
{
exampleBinary: { $binary: "PfvnbT7peNU/Sfvn" },
},
]);
})();
Insert documents 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 documents into the collection
(async function () {
const result = await collection.insertMany([
{
title: "Hidden Shadows of the Past",
genres: ["Biography", "Graphic Novel", "Dystopian", "Drama"],
metadata: {
isbn: "978-1-905585-40-3",
language: "French",
edition: "Anniversary Edition",
},
},
{
title: "Bake a Dozen",
genres: ["Biography", "Fiction"],
metadata: {
isbn: "342-2-875587-50-2",
language: "English",
edition: "Illustrated Edition",
},
},
]);
})();
Client reference
For more information, see the client reference.