Docs Menu

Insert Multiple Documents

You can insert multiple documents into a collection by using the InsertMany() method.

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

The server implicitly creates the necessary database and collection when you perform a write operation against them if they don't already exist.

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

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.

To learn more about inserting documents, see inserting documents.

InsertMany()

←  Insert a DocumentUpdate a Document →
Give Feedback
© 2022 MongoDB, Inc.

About

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