Chapter 6: Document Insertion in Golang MongoDB

Insert a Document

result, err := collection.InsertOne(
	context.Background(),  // Context parameter
	bson.D{   // Define a JSON document using bson.D
		{"item", "canvas"},
		{"qty", 100},
		{"tags", bson.A{"cotton"}},
		{"size", bson.D{
			{"h", 28},
			{"w", 35.5},
			{"uom", "cm"},
		}},
	})
	
// Obtain the unique ID generated for the document
id := result.InsertedID

Tip: If you're unfamiliar with Golang MongoDB data representation, please refer to the "Golang MongoDB Data Model" section here.

Equivalent to inserting the following JSON document:

{
	"item": "canvas",
	"qty": 100,
	"tags": ["cotton"],
	"size": {
		"h": 28,
		"w": 35.5,
		"uom": "cm"
	}
}

Query the Newly Inserted Document

cursor, err := collection.Find(
	context.Background(),
	bson.D{{"item", "canvas"}},  // Equivalent expression: {"item": "canvas"}
)

Bulk Insertion

result, err := collection.InsertMany(
	context.Background(),
	[]interface{}{   // Pass in an array of documents, insert three document data
		bson.D{ // Document data 1
			{"item", "journal"},
			{"qty", int32(25)},
			{"tags", bson.A{"blank", "red"}},
			{"size", bson.D{
				{"h", 14},
				{"w", 21},
				{"uom", "cm"},
			}},
		},
		bson.D{ // Document data 2
			{"item", "mat"},
			{"qty", int32(25)},
			{"tags", bson.A{"gray"}},
			{"size", bson.D{
				{"h", 27.9},
				{"w", 35.5},
				{"uom", "cm"},
			}},
		},
		bson.D{ // Document data 3
			{"item", "mousepad"},
			{"qty", 25},
			{"tags", bson.A{"gel", "blue"}},
			{"size", bson.D{
				{"h", 19},
				{"w", 22.85},
				{"uom", "cm"},
			}},
		},
	})

Query All Documents

cursor, err := collection.Find(
	context.Background(),
	bson.D{}, // Pass in an empty query condition
)