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.

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

documents

MaybeId<Schema>[]

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:

  • Field names cannot start with $.

  • Field names cannot be exactly *.

  • If a field name includes & or ., you must escape those characters when you use the field in a filter, sort, projection, or update. For more information, see Work with . and & in field names (TypeScript).

Reserved fields are tied to specific functionality. Include the following reserved fields in your documents, if applicable:

  • _id: An optional unique identifier for the document. If _id is omitted, it is created automatically based on the collection’s ID type. For more information, see Document IDs (TypeScript).

  • $vector: An optional array of numbers representing a vector embedding for vector search. The $vector field is only supported for vector-enabled collections.

For examples, see Examples.

options

CollectionInsertManyOptions

Optional. The options for this operation. See Properties of options for more details.

Properties of options
Name Type Summary

ordered

boolean

Optional. Whether the insertions must be processed sequentially. If False, the documents may be inserted in an arbitrary order and possibly concurrently. If you don’t need ordered inserts, DataStax recommends setting this parameter to False for faster performance.

concurrency

number

Optional. The maximum number of concurrent requests to the API at a given time.

If ordered is true, then concurrency must be 1 or unspecified.

For an example, see Insert documents and specify insertion behavior.

Default: 8 if ordered is false. 1 if ordered is true.

chunkSize

number

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: 100

Default: 50

timeout

number | TimeoutDescriptor

Optional.

The timeout(s) to apply to this method. You can specify requestTimeoutMs and generalMethodTimeoutMs.

For more information about the TimeoutDescriptor, see TypeScript client internals: TimeoutDescriptor. If you specify a number instead of a TimeoutDescriptor object, that number will be applied to generalMethodTimeoutMs.

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 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.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM