Insert Multiple Documents
You can insert multiple documents into a collection by using the InsertMany()
method.
Example
Tip
Read the Usage Examples to learn how to run this example.
The following example inserts two documents in the haikus
collection:
Tip
Non-existent Databases and Collections
If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.
coll := client.Database("insertDB").Collection("haikus") docs := []interface{}{ bson.D{{"title", "Record of a Shriveled Datum"}, {"text", "No bytes, no problem. Just insert a document, in MongoDB"}}, bson.D{{"title", "Showcasing a Blossoming Binary"}, {"text", "Binary data, safely stored with GridFS. Bucket the data"}}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) }
View a fully runnable example
Expected Result
After you run the full example, you can find the following inserted
documents in the haikus
collection:
{ "_id": ObjectId("..."), "title": "Record of a Shriveled Datum", "text": "No bytes, no problem. Inserting a document. In MongoDB" }, { "_id": ObjectId("..."), "title": "Showcasing a Blossoming Binary", "text": "Binary data, safely stored with GridFS. Bucket the data" }
For an example on how to find multiple documents, see Find Multiple Documents.
Additional Information
To learn more about inserting documents, see inserting documents.