Docs Menu

Docs HomeGo

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 need to insert those documents. You can insert one document using the InsertOne() method, or insert multiple documents using either the InsertMany() or BulkWrite() method.

The following sections focus on InsertOne() and InsertMany().

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

The two options for managing this field are:

  • You can manage this field yourself, ensuring each value you use is unique.

  • You can let 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.

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

coll := client.Database("myDB").Collection("favorite_books")
doc := bson.D{{"title", "Invisible Cities"}, {"author", "Italo Calvino"}, {"year_published", 1974}}
result, err := coll.InsertOne(context.TODO(), doc)
fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)

You can modify the behavior of InsertOne() by constructing and passing an optional InsertOneOptions struct. The available options to tune 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 some documents into the favorite_books collection using the InsertMany() method:

coll := client.Database("myDB").Collection("favorite_books")
docs := []interface{}{
bson.D{{"title", "My Brilliant Friend"}, {"author", "Elena Ferrante"}, {"year_published", 2012}},
bson.D{{"title", "Lucy"}, {"author", "Jamaica Kincaid"}, {"year_published", 2002}},
bson.D{{"title", "Cat's Cradle"}, {"author", "Kurt Vonnegut Jr."}, {"year_published", 1998}},
}
result, err := coll.InsertMany(context.TODO(), docs)
list_ids := result.InsertedIDs
fmt.Printf("Documents inserted: %v\n", len(list_ids))
for _, id := range list_ids {
fmt.Printf("Inserted document with _id: %v\n", id)
}

Your output should look like this:

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 InsertOneOptions struct. The available options to tune with InsertOneOptions 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 abort 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, "country": "Tanzania" }
{ "_id": 2, "country": "Lithuania" }
{ "_id": 1, "country": "Vietnam" }
{ "_id": 3, "country": "Argentina" }

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:

docs := []interface{}{
bson.D{{"_id", 1}, {"country", "Tanzania"}},
bson.D{{"_id", 2}, {"country", "Lithuania"}},
bson.D{{"_id", 1}, {"country", "Vietnam"}},
bson.D{{"_id", 3}, {"country", "Argentina"}},
}
result, err := coll.InsertMany(context.TODO(), docs)
list_ids := result.InsertedIDs
if err != nil {
fmt.Printf("A bulk write error occurred, but %v documents were still inserted.\n", len(list_ids))
}
for _, id := range list_ids {
fmt.Printf("Inserted document with _id: %v\n", id)
}

If you look inside your collection, you should be able to see the following documents:

{ "_id": 1, "country": "Tanzania" }
{ "_id": 2, "country": "Lithuania" }

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:

←  Write OperationsDelete a Document →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.