Document IDs (Go)
_id field
Documents in a collection are always identified by an ID that is unique within the collection.
This identifier is stored in the reserved field _id.
Default document IDs
When you create a collection, you can specify the default ID type for documents in the collection. The Data API supports Object IDs, version 4 UUIDs, version 6 UUIDs, and version 7 UUIDs. If you don’t specify the default ID type, the default type is a string form of a version 4 UUID.
If you don’t explicitly set the _id field when you insert a document into the collection, the Data API will automatically generate the _id field based on the default ID type for the collection.
For more information about setting the default ID type, see Create a collection (Go).
Specifying document IDs
DataStax recommends using the automatically generated document ID instead of specifying the ID.
This ensures uniqueness across the database and reduces the complexity of your code.
However, you can use the reserved _id field to specify a document ID when you insert a document.
For examples, see Insert documents and specify the IDs.
If you try to insert a document with an _id field that is not unique in the collection, the Data API will throw an error.
If you explicitly set the _id field, it must be one of the allowed types: string, number, date, Boolean, or null.
Deduplicating documents
If you want to prevent duplicate documents, you can generate the document’s _id as a hash of one or more fields.
Because the Data API enforces uniqueness on the _id field, attempting to insert a document with an existing _id results in an error.
Your application can catch that error and skip inserting the duplicate.
The following example shows how to generate the _id as a stable hash of a single field named content.
If a document’s identity depends on multiple fields, you can instead hash a canonicalized representation of those fields.
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"log"
"github.com/datastax/astra-db-go/v2/astra"
"github.com/datastax/astra-db-go/v2/astra/options"
"github.com/datastax/astra-db-go/v2/astra/results"
)
func main() {
ctx := context.Background()
// Get an existing collection
client := astra.NewClient()
database := client.Database(
"API_ENDPOINT",
options.API().SetToken("APPLICATION_TOKEN"),
)
collection := database.Collection("COLLECTION_NAME")
// Example document
document := map[string]any{
"title": "Example article",
"content": "This is the main text of the document. _id is generated from this field so that this field is never duplicated across documents.",
"source": "https://example.com",
}
// Derive a deterministic _id based on the "content" field
content := document["content"].(string)
hash := sha256.Sum256([]byte(content))
document["_id"] = hex.EncodeToString(hash[:])
// Try to insert the document
result, err := collection.InsertOne(ctx, document)
if err != nil {
// Check for DOCUMENT_ALREADY_EXISTS error
var apiErrs *results.DataAPIErrors
if errors.As(err, &apiErrs) {
for _, apiErr := range *apiErrs {
if apiErr.ErrorCode == "DOCUMENT_ALREADY_EXISTS" {
fmt.Println(
"Document already exists with this _id; skipping insert.",
)
return
}
}
}
// Handle all other errors
log.Fatalf("Failed to insert document: %v", err)
}
insertedID, err := result.RawID()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Inserted new document with _id: %v\n", insertedID)
}
Other document identifiers
Regardless of the collection’s default ID type, you can use document identifiers of any type outside of the reserved _id field.
The Data API does not force uniqueness across identifiers outside of the _id field.