How to Perform CRUD Operations with MongoDB in Go

Connect to MongoDB in Go and perform Create, Read, Update, and Delete operations using the official driver and BSON.

Use the official MongoDB Go driver to connect to your database and execute CRUD operations via the Collection object.

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/bson"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)

	collection := client.Database("mydb").Collection("users")

	// Create
	_, err = collection.InsertOne(ctx, bson.D{{"name", "Alice"}, {"age", 30}})
	if err != nil {
		log.Fatal(err)
	}

	// Read
	var result bson.M
	err = collection.FindOne(ctx, bson.D{{"name", "Alice"}}).Decode(&result)
	if err != nil {
		log.Fatal(err)
	}

	// Update
	_, err = collection.UpdateOne(ctx, bson.D{{"name", "Alice"}}, bson.D{{"$set", bson.D{{"age", 31}}}})
	if err != nil {
		log.Fatal(err)
	}

	// Delete
	_, err = collection.DeleteOne(ctx, bson.D{{"name", "Alice"}})
	if err != nil {
		log.Fatal(err)
	}
}