Insert documents (C#)

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 (C#).

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 CollectionInsertManyResult object that includes the IDs of the inserted documents.

Unless the document ID was specified, the ID value depends on the default ID type. For more information, see Document IDs (C#).

Parameters

Use the InsertManyAsync method, which belongs to the Collection class. You can also use InsertMany, which is the synchronous version of the method.

Method signature
public Task<CollectionInsertManyResult<TId>> InsertManyAsync(
  List<T> documents,
  CollectionInsertManyOptions options = null
);
Name Type Summary

documents

List<T>

A list of objects describing the 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 (C#).

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 (C#).

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

  • $lexical: An optional string to make the document searchable for lexicographical matching. The $lexical field is only supported for collections that have lexical search enabled. For more information, see $lexical in collections (C#).

For examples, see Examples.

With the C# client, if you specify a type for your documents instead of using the generic Document class, you can use the DocumentMapping attribute for the $vector, $vectorize, or $lexical fields or the $hybrid shorthand. For more information and examples, see Custom typing for collections.

options

CollectionInsertManyOptions

Optional. Options for this operation. For more information and examples for general options such as timeout, see Customize API interaction. For options specific to this method, see Method-specific properties of the CollectionInsertManyOptions class.

Method-specific properties of the CollectionInsertManyOptions class
Name Type Summary

Ordered

bool

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.

Default: false.

Concurrency

int

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: 20 if Ordered is False. 1 if Ordered is True.

ChunkSize

int

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

Examples

The following examples demonstrate how to insert multiple documents into a collection.

Insert documents

The documents can have different structures.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient(
      new CommandOptions() { Destination = DataAPIDestination.HCD }
    );

    var database = client.GetDatabase(
      "API_ENDPOINT",
      DataAPIClient.UsernamePasswordTokenProvider(
        "USERNAME",
        "PASSWORD"
      ),
      "KEYSPACE_NAME"
    );

    var collection = database.GetCollection("COLLECTION_NAME");

    // Insert documents to the collection
    var document1 = new Document()
    {
      { "name", "Jane Doe" },
      { "age", 42 },
    };
    var document2 = new Document()
    {
      { "nickname", "Bobby" },
      { "color", "blue" },
      { "foods", new[] { "carrots", "chocolate" } },
    };
    var result = await collection.InsertManyAsync([document1, document2]);

    foreach (var id in result.InsertedIds)
    {
      Console.WriteLine(id);
    }
  }
}

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 (C#).

You may also insert a mix of documents with and without the $vector field.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections. Specifically, you can use the [DocumentMapping(DocumentMappingField.Vector)] attribute.

using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient(
      new CommandOptions() { Destination = DataAPIDestination.HCD }
    );

    var database = client.GetDatabase(
      "API_ENDPOINT",
      DataAPIClient.UsernamePasswordTokenProvider(
        "USERNAME",
        "PASSWORD"
      ),
      "KEYSPACE_NAME"
    );

    var collection = database.GetCollection("COLLECTION_NAME");

    // Insert documents to the collection
    var document1 = new Document()
    {
      { "$vector", new double[] { 0.08f, -0.62f, 0.39f } },
      { "name", "Jane Doe" },
      { "age", 42 },
    };
    var document2 = new Document()
    {
      { "$vector", new double[] { 0.12f, 0.53f, 0.32f } },
      { "nickname", "Bobby" },
    };
    var result = await collection.InsertManyAsync([document1, document2]);

    foreach (var id in result.InsertedIds)
    {
      Console.WriteLine(id);
    }
  }
}

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.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient(
      new CommandOptions() { Destination = DataAPIDestination.HCD }
    );

    var database = client.GetDatabase(
      "API_ENDPOINT",
      DataAPIClient.UsernamePasswordTokenProvider(
        "USERNAME",
        "PASSWORD"
      ),
      "KEYSPACE_NAME"
    );

    var collection = database.GetCollection("COLLECTION_NAME");

    // Insert documents to the collection
    var document1 = new Document()
    {
      { "name", "Jane Doe" },
      { "$lexical", "An author who writes SciFi and fantasy novels." },
    };
    var document2 = new Document()
    {
      { "name", "Mary Day" },
      {
        "$lexical",
        "An active hiker, runner, and triathlete who loves the outdoors."
      },
    };
    var result = await collection.InsertManyAsync([document1, document2]);

    foreach (var id in result.InsertedIds)
    {
      Console.WriteLine(id);
    }
  }
}

Insert documents and specify the IDs

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections. Specifically, you can use the [DocumentId] attribute.

using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient(
      new CommandOptions() { Destination = DataAPIDestination.HCD }
    );

    var database = client.GetDatabase(
      "API_ENDPOINT",
      DataAPIClient.UsernamePasswordTokenProvider(
        "USERNAME",
        "PASSWORD"
      ),
      "KEYSPACE_NAME"
    );

    var collection = database.GetCollection("COLLECTION_NAME");

    // Insert documents to the collection
    var document1 = new Document()
    {
      { "name", "Melissa" },
      { "_id", Guid.CreateVersion7() },
    };
    var document2 = new Document()
    {
      { "name", "Bobby" },
      { "_id", "b_023" },
    };
    var result = await collection.InsertManyAsync([document1, document2]);

    foreach (var id in result.InsertedIds)
    {
      Console.WriteLine(id);
    }
  }
}

Insert documents and specify insertion behavior

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient(
      new CommandOptions() { Destination = DataAPIDestination.HCD }
    );

    var database = client.GetDatabase(
      "API_ENDPOINT",
      DataAPIClient.UsernamePasswordTokenProvider(
        "USERNAME",
        "PASSWORD"
      ),
      "KEYSPACE_NAME"
    );

    var collection = database.GetCollection("COLLECTION_NAME");

    // Insert documents to the collection
    var document1 = new Document()
    {
      { "name", "Jane Doe" },
      { "age", 42 },
    };
    var document2 = new Document()
    {
      { "nickname", "Bobby" },
      { "color", "blue" },
      { "foods", new[] { "carrots", "chocolate" } },
    };
    var options = new CollectionInsertManyOptions()
    {
      ChunkSize = 2,
      Concurrency = 2,
      Ordered = false,
    };
    var result = await collection.InsertManyAsync(
      [document1, document2],
      options
    );

    foreach (var id in result.InsertedIds)
    {
      Console.WriteLine(id);
    }
  }
}

Insert documents with a binary field

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient(
      new CommandOptions() { Destination = DataAPIDestination.HCD }
    );

    var database = client.GetDatabase(
      "API_ENDPOINT",
      DataAPIClient.UsernamePasswordTokenProvider(
        "USERNAME",
        "PASSWORD"
      ),
      "KEYSPACE_NAME"
    );

    var collection = database.GetCollection("COLLECTION_NAME");

    // Insert documents to the collection
    var result = await collection.InsertManyAsync(
      [
        new Document()
        {
          {
            "exampleBinary",
            new byte[]
            {
              0x3D,
              0xFB,
              0xE7,
              0x6D,
              0x3E,
              0xE9,
              0x78,
              0xD5,
              0x3F,
              0x49,
              0xFB,
              0xE7,
            }
          },
        },
      ]
    );

    foreach (var id in result.InsertedIds)
    {
      Console.WriteLine(id);
    }
  }
}

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.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient(
      new CommandOptions() { Destination = DataAPIDestination.HCD }
    );

    var database = client.GetDatabase(
      "API_ENDPOINT",
      DataAPIClient.UsernamePasswordTokenProvider(
        "USERNAME",
        "PASSWORD"
      ),
      "KEYSPACE_NAME"
    );

    var collection = database.GetCollection("COLLECTION_NAME");

    // Insert documents to the collection
    var document1 = new Document()
    {
      { "title", "Hidden Shadows of the Past" },
      {
        "genres",
        new List<string>
        {
          "Biography",
          "Graphic Novel",
          "Dystopian",
          "Drama",
        }
      },
      {
        "metadata",
        new Dictionary<string, object?>
        {
          { "isbn", "978-1-905585-40-3" },
          { "language", "French" },
          { "edition", "Anniversary Edition" },
        }
      },
    };
    var document2 = new Document()
    {
      { "title", "Bake a Dozen" },
      {
        "genres",
        new List<string> { "Biography", "Fiction" }
      },
      {
        "metadata",
        new Dictionary<string, object?>
        {
          { "isbn", "342-2-875587-50-2" },
          { "language", "English" },
          { "edition", "Illustrated Edition" },
        }
      },
    };
    var result = await collection.InsertManyAsync([document1, document2]);

    foreach (var id in result.InsertedIds)
    {
      Console.WriteLine(id);
    }
  }
}

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