Overview
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.
The _id Field
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 uniqueObjectId
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.
Insert a Document
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.
Example
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("...")
Modify InsertOne() Behavior
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 |
---|---|
| If true , allows the write to opt-out of document level validation.Default: false |
Construct an InsertOneOptions
as follows:
opts := options.InsertOne().SetBypassDocumentValidation(true)
Insert a Document Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Create a MongoClient guide. This example
also uses the restaurants
collection in the sample_restaurants
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas
by following the Get Started with Atlas Guide.
The following example inserts a new document into the restaurants
collection.
Select the Struct or bson.D tab to see the corresponding code:
The following code uses a struct to insert a new document into the
restaurants
collection:
// Inserts a single document describing a restaurant by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines the structure of a restaurant document type Restaurant struct { Name string RestaurantId string `bson:"restaurant_id,omitempty"` Cuisine string `bson:"cuisine,omitempty"` Address interface{} `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []interface{} `bson:"grades,omitempty"` } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() // Inserts a sample document describing a restaurant into the collection coll := client.Database("sample_restaurants").Collection("restaurants") newRestaurant := Restaurant{Name: "8282", Cuisine: "Korean"} result, err := coll.InsertOne(context.TODO(), newRestaurant) if err != nil { panic(err) } // Prints the ID of the inserted document fmt.Printf("Document inserted with ID: %s\n", result.InsertedID) }
Document inserted with ID: ObjectID("...")
The following code uses a bson.D
type to insert a new document into the
restaurants
collection:
// Inserts a single document describing a restaurant by using the Go driver with bson.D package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() // Inserts a sample document describing a restaurant into the collection using bson.D coll := client.Database("sample_restaurants").Collection("restaurants") newRestaurant := bson.D{ bson.E{Key: "name", Value: "8282"}, bson.E{Key: "cuisine", Value: "Korean"}, } result, err := coll.InsertOne(context.TODO(), newRestaurant) if err != nil { panic(err) } // Prints the ID of the inserted document fmt.Printf("Document inserted with ID: %s\n", result.InsertedID) }
Document inserted with ID: ObjectID("...")
Insert Multiple Documents
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.
Example
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("...")
Modify InsertMany() Behavior
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 |
---|---|
| If true , allows the write to opt-out of document level validation.Default: false |
| 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)
Ordered Behavior
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" }
Insert Many Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Create a MongoClient guide. This example
also uses the restaurants
collection in the sample_restaurants
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas
by following the Get Started with Atlas Guide.
The following example inserts multiple new documents into the restaurants
collection.
Select the Struct or bson.D tab to see the corresponding code:
The following code uses a struct to insert multiple new documents into the
restaurants
collection:
// Inserts sample documents describing restaurants by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines the structure of a restaurant document type Restaurant struct { Name string RestaurantId string `bson:"restaurant_id,omitempty"` Cuisine string `bson:"cuisine,omitempty"` Address interface{} `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []interface{} `bson:"grades,omitempty"` } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") // Creates two sample documents describing restaurants newRestaurants := []interface{}{ Restaurant{Name: "Rule of Thirds", Cuisine: "Japanese"}, Restaurant{Name: "Madame Vo", Cuisine: "Vietnamese"}, } // Inserts sample documents into the collection result, err := coll.InsertMany(context.TODO(), newRestaurants) if err != nil { panic(err) } // Prints the IDs of the inserted documents fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("\t%s\n", id) } }
2 documents inserted with IDs: ObjectID("...") ObjectID("...")
The following code uses a bson.D
type to insert multiple new documents into the
restaurants
collection:
// Inserts sample documents describing restaurants by using the Go driver with bson.D package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") // Creates two sample documents describing restaurants using bson.D newRestaurants := []interface{}{ bson.D{ bson.E{Key: "name", Value: "Rule of Thirds"}, bson.E{Key: "cuisine", Value: "Japanese"}, }, bson.D{ bson.E{Key: "name", Value: "Madame Vo"}, bson.E{Key: "cuisine", Value: "Vietnamese"}, }, } // Inserts sample documents into the collection result, err := coll.InsertMany(context.TODO(), newRestaurants) if err != nil { panic(err) } // Prints the IDs of the inserted documents fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("\t%s\n", id) } }
2 documents inserted with IDs: ObjectID("...") ObjectID("...")
Additional Information
To learn more about performing the operations mentioned, see the following guides:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: