Docs Menu

Docs HomeGo

Insert a Document

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


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

The following example inserts a document in the haikus collection:


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 {

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.


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


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