Insert a Document
You can insert a document into a collection by using the InsertOne()
method.
Example
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
Expected Result
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.
Additional Information
To learn more about inserting documents, see inserting documents.