Insert a document (Go)

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 (Go).

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 an *InsertOneResult struct that includes the ID of the inserted document, which you can access with the RawID() or DecodeID(v any) methods.

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

Parameters

Use the InsertOne method, which belongs to the Collection type.

Method signature
func (c *Collection) InsertOne(
  ctx context.Context,
  document any,
  opts ...options.CollectionInsertOneOption
) (*results.InsertOneResult, error)
Name Type Summary

ctx

context.Context

The context for the operation.

document

any

A struct or map describing a 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:

  • 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 (Go).

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 (Go).

  • $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 (Go).

For examples, see Examples.

opts

…​options.CollectionInsertOneOption

Optional. A builder to generate options for this operation. See Methods of the CollectionInsertOneOption builder for more details.

Methods of the CollectionInsertOneOption builder
Method Summary

UpdateAPIOptions(v …​APIOption)

Optional. General API options for this operation, including the timeout.

Examples

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

Insert a document

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document into the collection
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			"title": "Hidden Shadows of the Past",
			"genres": []string{
				"Biography",
				"Graphic Novel",
				"Dystopian",
				"Drama",
			},
			"metadata": map[string]any{
				"isbn":     "978-1-905585-40-3",
				"language": "French",
				"edition":  "Anniversary Edition",
			},
			"number_of_pages": 245,
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

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 (Go).

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document into the collection
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			"name":    "Jane Doe",
			"$vector": []float32{0.08, -0.62, 0.39},
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

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.

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document into the collection
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			"name":     "Jane Doe",
			"$lexical": "An active hiker, runner, and triathlete who loves the outdoors.",
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

Insert a document and specify the ID

The Go client provides methods like datatypes.NewObjectId() and datatypes.NewUUIDv7() to use and generate identifiers.

Example creating a UUID:

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/datatypes"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document into the collection
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			"_id":  datatypes.NewUUIDv7(),
			"name": "Jane Doe",
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

Example creating an ObjectID:

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/datatypes"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document into the collection
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			"_id":  datatypes.NewObjectId(),
			"name": "Jane Doe",
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

Example specifying the ID without a UUID or ObjectId method:

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document into the collection
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			"_id":  1,
			"name": "Jane Doe",
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

Insert a document with a binary field

You can insert binary data as a []byte slice or a Base64-encoded string with $binary. []byte slices are automatically Base64-encoded.

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document with binary fields
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			// Using $binary with a Base64-encoded string
			"exampleBinary": map[string]any{
				"$binary": "PfvnbT7peNU/Sfvn",
			},
			// No need for explicit '$binary' with a byte array
			"anotherExampleBinary": []byte{
				0x3d,
				0xfb,
				0xe7,
				0x6d,
				0x3e,
				0xe9,
				0x78,
				0xd5,
				0x3f,
				0x49,
				0xfb,
				0xe7,
			},
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

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.

package main

import (
	"context"
	"log"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	ctx := context.Background()
	// Get an existing collection
	client := astra.NewClient(
		options.API().SetEnvironment(options.EnvironmentHCD),
	)

	database := client.Database(
		"API_ENDPOINT",
		options.API().
			SetUsernamePasswordTokenProvider(
				"USERNAME",
				"PASSWORD",
			).
			SetKeyspace("KEYSPACE_NAME"),
	)

	collection := database.Collection("COLLECTION_NAME")

	// Insert a document into the collection
	_, err := collection.InsertOne(
		ctx,
		map[string]any{
			"title": "Hidden Shadows of the Past",
			"genres": []string{
				"Biography",
				"Graphic Novel",
				"Dystopian",
				"Drama",
			},
			"metadata": map[string]any{
				"isbn":     "978-1-905585-40-3",
				"language": "French",
				"edition":  "Anniversary Edition",
			},
		},
	)
	if err != nil {
		log.Fatal(err)
	}
}

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