Docs Menu
Docs Home
/ / /
Go Driver
/ / /

Insert a Document

On this page

  • Overview
  • The _id Field
  • Insert a Document
  • Example
  • Modify InsertOne Behavior
  • Insert Multiple Documents
  • Example
  • Modify InsertMany Behavior
  • Ordered Behavior
  • Additional Information
  • API Documentation

In this guide, you can learn how to insert documents into a MongoDB collection.

Before you can find, update, and delete documents in MongoDB, you must insert those documents. You can insert one document by using the InsertOne() method, or insert multiple documents by using either the InsertMany() or BulkWrite() method.

The following sections focus on InsertOne() and InsertMany(). To learn how to use the BulkWrite() method, see the Bulk Operations guide.

In MongoDB, each document must contain a unique _id field.

The two options for managing this field are:

  • Managing this field yourself, ensuring that each value you use is unique.

  • Letting the driver automatically generate unique ObjectId values. The driver generates unique ObjectId values for documents that you do not explicitly specify an _id.

Unless you provide strong guarantees for uniqueness, MongoDB recommends you let the driver automatically generate _id values.

Note

Duplicate _id values violate unique index constraints, which causes the driver to return a WriteError.

To learn more about the _id field, see the Server Manual Entry on Unique Indexes.

To learn more about document structure and rules, see the Server Manual Entry on Documents.

Use the InsertOne() method to insert a single document into a collection.

Upon successful insertion, the method returns an InsertOneResult instance that contains the _id of the new document.

This example uses the following Book struct as a model for documents in the books collection:

type Book struct {
Title string
Author string
}

The following example creates and inserts a document into the books collection using the InsertOne() method:

coll := client.Database("db").Collection("books")
doc := Book{Title: "Atonement", Author: "Ian McEwan"}
result, err := coll.InsertOne(context.TODO(), doc)
fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)
Inserted document with _id: ObjectID("...")

You can modify the behavior of InsertOne() by constructing and passing an optional InsertOneOptions struct. The available options to set with InsertOneOptions are:

Option
Description
BypassDocumentValidation
If true, allows the write to opt-out of document level validation.
Default: false

Construct an InsertOneOptions as follows:

opts := options.InsertOne().SetBypassDocumentValidation(true)

Use the InsertMany() method to insert multiple documents into a collection.

Upon successful insertion, the InsertMany() method returns an InsertManyResult instance that contains the _id fields of the inserted documents.

The following example creates and inserts multiple documents into the books collection using the InsertMany() method:

coll := client.Database("myDB").Collection("favorite_books")
docs := []interface{}{
Book{Title: "Cat's Cradle", Author: "Kurt Vonnegut Jr."},
Book{Title: "In Memory of Memory", Author: "Maria Stepanova"},
Book{Title: "Pride and Prejudice", Author: "Jane Austen"},
}
result, err := coll.InsertMany(context.TODO(), docs)
fmt.Printf("Documents inserted: %v\n", len(result.InsertedIDs))
for _, id := range result.InsertedIDs {
fmt.Printf("Inserted document with _id: %v\n", id)
}

After running the preceding code, your output resembles the following:

Documents inserted: 3
Inserted document with _id: ObjectID("...")
Inserted document with _id: ObjectID("...")
Inserted document with _id: ObjectID("...")

You can modify the behavior of InsertMany() by constructing and passing an optional InsertManyOptions struct. The available options to set with InsertManyOptions are:

Option
Description
BypassDocumentValidation
If true, allows the write to opt-out of document level validation.
Default: false
Ordered
If true, the driver sends documents to the server in the order provided. If an error occurs, the driver and server end all remaining insert operations. To learn more, see Ordered Behavior.
Default: false

Construct an InsertManyOptions as follows:

opts := options.InsertMany().SetBypassDocumentValidation(true).SetOrdered(false)

Assume you want to insert the following documents:

{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }
{ "_id": 1, "title": "Blueberries for Sal" }
{ "_id": 3, "title": "Goodnight Moon" }

If you attempt to insert these documents with default InsertManyOptions, a BulkWriteException occurs at the third document because of the repeated _id value, but the documents before the error-producing document still get inserted into your collection.

Note

You can get an acknowledgement of successful document insertion even if a BulkWriteException occurs:

type Book struct {
ID int `bson:"_id"`
Title string
}
...
docs := []interface{}{
Book{ID: 1, Title: "Where the Wild Things Are"},
Book{ID: 2, Title: "The Very Hungry Caterpillar"},
Book{ID: 1, Title: "Blueberries for Sal"},
Book{ID: 3, Title: "Goodnight Moon"},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
fmt.Printf("A bulk write error occurred, but %v documents were still inserted.\n", len(result.InsertedIDs))
}
for _, id := range result.InsertedIDs {
fmt.Printf("Inserted document with _id: %v\n", id)
}
A bulk write error occurred, but 2 documents were still inserted.
Inserted document with _id: 1
Inserted document with _id: 2

After running the preceding code, your collection contains the following documents:

{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }

For runnable examples of the insert operations, see the following usage examples:

To learn more about performing the operations mentioned, see the following guides:

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

Back

Write