Docs Menu

Docs HomeGo

Insert a Document

You can insert a document into a collection by using the InsertOne() method.

Tip

Read the Usage Examples to learn how to run this example.

The following example inserts a document 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")
doc := bson.D{{"title", "Record of a Shriveled Datum"}, {"text", "No bytes, no problem. Just insert a document, in MongoDB"}}
result, err := coll.InsertOne(context.TODO(), doc)
if err != nil {
panic(err)
}

View a fully runnable example

After you run the full example, you can find the following inserted document in the haikus collection:

{
"_id": ObjectId("..."),
"title": "Record of a Shriveled Datum",
"text": "No bytes, no problem. Inserting a document. In MongoDB"
}

For an example on how to find a document, see Find a Document.

To learn more about inserting documents, see inserting documents.

InsertOne()

←  Write OperationsInsert Multiple Documents →
Give Feedback
© 2022 MongoDB, Inc.

About

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