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.

This example uses the following Restaurant struct as a model for documents in the restaurants collection:

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"`
}

The omitempty struct tag omits the corresponding field from the inserted document when left empty.

The following example inserts a new document to the restaurants 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("sample_restaurants").Collection("restaurants")
newRestaurant := Restaurant{Name: "8282", Cuisine: "Korean"}
result, err := coll.InsertOne(context.TODO(), newRestaurant)
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 restaurants collection:

{
"_id": ObjectId("..."),
"name": "8282",
"cuisine": "Korean"
}

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

To learn more about inserting documents, see inserting documents.

InsertOne()

←  Write OperationsInsert Multiple Documents →