Insert a document

Inserts a single document into a collection.

Documents are stored in collections. They represent a single row or record of data in Astra DB Serverless databases. For more information, see Work with collections and Work with documents.

If the collection is vector-enabled, pregenerated vector embeddings can be included by using the reserved $vector field. If the collection has vectorize enabled, vector embeddings can be automatically generated from text specified in the reserved $vectorize field.

Result

  • Python

  • TypeScript

  • Java

  • curl

Inserts the specified document and returns an InsertOneResult object that includes the ID of the inserted document and details about the success of the operation.

The ID value depends on the ID type. For more information, see Document IDs.

Example response:

InsertOneResult(inserted_id='92b3c4f4-db44-4440-b4c4-f4db54e440b8', raw_results=...)

Inserts the specified document and returns a promise that resolves to an InsertOneResult<Schema> object that includes the ID of the inserted document.

The ID value depends on the ID type. For more information, see Document IDs.

Example response:

{ insertedId: '92b3c4f4-db44-4440-b4c4-f4db54e440b8' }

Inserts the specified document and returns a wrapper (InsertOneResult) that includes the ID of the inserted document.

The ID value depends on the ID type. For more information, see Document IDs.

Inserts the specified document and returns a JSON object that includes the ID of the inserted document.

The ID value depends on the ID type. For more information, see Document IDs.

Example response:

{
  "status": {
    "insertedIds": [
      "3f557bef-fd53-47ea-957b-effd53c7eaec"
    ]
  }
}

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Name Type Summary

document

Dict

The dictionary expressing the document to insert. The _id field of the document can be left out, in which case it will be created automatically. The document may contain the $vector or the $vectorize fields, but not both.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the underlying HTTP request. If not passed, the collection-level setting is used instead.

Name Type Summary

document

MaybeId<Schema>

The document to insert. If the document does not have an _id field, the server generates one. It may contain a $vector or $vectorize field to enable semantic searching.

options?

InsertOneOptions

The options for this operation.

Options (InsertOneOptions):

Name Type Summary

maxTimeMS?

number

The maximum time in milliseconds that the client should wait for the operation to complete.

Name Type Summary

document

DOC

Object representing the document to insert. The _id field of the document can be left out, in which case it will be created automatically. If the collection is associated with an embedding service, it will generate an embedding automatically from the $vectorize field.

embeddings

float[]

A vector of embeddings (a list of numbers appropriate for the collection) for the document. Passing this parameter is equivalent to providing the vector in the $vector field of the document itself.

Name Type Summary

insertOne

command

Data API command to insert one document in a collection.

document

object

Contains the details of the record to add.

With the exception of reserved fields (_id, $vector, and $vectorize), document data can be any valid JSON, including strings, integers, booleans, dates, objects, nested objects, and arrays:

    "document": {
      "string_example": "string value",
      "object_example": {
        "a": "one",
        "b": 2,
        "nested_object": {
          "c": false
        }
      },
      "date_example": { "$date": 1690045891 },
      "array_example": [
        {
          "d.e": "hello",
          "f.g": "goodbye"
        },
        "arbitrary string in an array"
      ]
    }

_id

reserved, multi-type

An optional identifier for the document. If omitted, the server automatically generates a document ID. You can include identifiers in other fields as well. For more information, see Document IDs and The defaultId option.

$vector

reserved array

An optional reserved property used to store an array of numbers representing a vector embedding. Serverless (Vector) databases have specialized handling for vector data, including optimized query performance for vector search.

$vector and $vectorize are mutually exclusive.

$vectorize

reserved string

An optional reserved property used to store a string that you want to use to automatically generate an embedding with vectorize.

$vector and $vectorize are mutually exclusive.

Examples

The following examples demonstrate how to insert a document into a collection.

Insert a document

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one({
    "name": "Jane Doe",
    "age": 42
})
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    name: 'Jane Doe',
    age: 42
  });
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.InsertOneResult;

public class InsertOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Insert a document into the collection
        Document document = new Document()
            .append("name", "Jane Doe")
            .append("age", 42);
        InsertOneResult result = collection.insertOne(document);
        System.out.println(result.getInsertedId());
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/COLLECTION_NAME" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "insertOne": {
    "document": {
      "purchase_type": "Online",
      "customer": {
        "name": "Jim A.",
        "phone": "123-456-1111",
        "age": 51,
        "credit_score": 782,
        "address": {
          "street": "1234 Broadway",
          "city": "New York",
          "state": "NY"
        }
      },
      "purchase_date": { "$date": 1690045891 },
      "seller": {
        "name": "Jon B.",
        "location": "Manhattan NYC"
      },
      "items": [
        {
          "car": "BMW 330i Sedan",
          "color": "Silver"
        },
        "Extended warranty - 5 years"
      ],
      "amount": 47601,
      "status": "active",
      "preferred_customer": true
    }
  }
}'

Insert a document with vector embeddings

Use the reserved $vector field to insert a document with pregenerated vector embeddings.

The $vector field is only supported for vector-enabled collections. For more information, see Vector and vectorize.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient


# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
      "name": "Jane Doe",
      "$vector": [.08, .68, .30],
    },
)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
  name: 'Jane Doe',
  $vector: [.08, .68, .30],
});
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.InsertOneResult;

public class InsertOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Insert a document into the collection
        Document document = new Document()
            .append("name", "Jane Doe")
            .append("age", 42);
        InsertOneResult result = collection.insertOne(
            document,
            new float[] {.08f, .68f, .30f}
        );
        System.out.println(result.getInsertedId());
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/COLLECTION_NAME" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "insertOne": {
    "document": {
      "name": "Jane Doe",
      "$vector": [.08, .68, .30]
    }
  }
}'

Insert a document and generate vector embeddings

Use the reserved $vectorize field to generate a vector embedding automatically. The value of $vectorize can be any string.

The $vectorize field is only supported for collections that have vectorize enabled. For more information, see Vector and vectorize and Auto-generate embeddings with vectorize.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient


# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
      "name": "Jane Doe",
      "$vectorize": "Text to vectorize",
    },
)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    name: 'Jane Doe',
    $vectorize: 'Text to vectorize',
  });
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.InsertOneResult;

public class InsertOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Insert a document into the collection
        Document document = new Document()
            .append("name", "Jane Doe")
            .append("$vectorize", "Text to vectorize");
        InsertOneResult result = collection.insertOne(document);
        System.out.println(result.getInsertedId());
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/COLLECTION_NAME" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "insertOne": {
    "document": {
      "name": "Jane Doe",
      "$vectorize": "Text to vectorize"
    }
  }
}'

Insert a document and specify the ID

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient


# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
        "_id": 1,
        "name": "Jane Doe",
    },
)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    _id: '1',
    name: 'Jane Doe',
  });
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.InsertOneResult;

public class InsertOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Insert a document into the collection
        Document document = new Document("1")
            .append("name", "Jane Doe")
            .append("age", 42);
        InsertOneResult result = collection.insertOne(document);
        System.out.println(result.getInsertedId());
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/COLLECTION_NAME" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "insertOne": {
    "document": {
      "name": "Jane Doe",
      "_id": "1"
    }
  }
}'

Client reference

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the client reference.

For more information, see the client reference.

For more information, see the client reference.

Client reference documentation is not applicable for HTTP.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | 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: +1 (650) 389-6000, info@datastax.com