MongoDB is a popular NoSQL database that is used for storing and querying large volumes of unstructured data. In this article, we will explore how to interact with MongoDB using the Go programming language by performing basic CRUD (Create, Read, Update, Delete) operations.

Setting up the Go Environment

First, you need to install Go on your machine. You can download it from the official website. Once installed, verify the installation by running the command:

go version

Create a new directory for your project:

mkdir go-mongodb
cd go-mongodb

Installing the MongoDB Driver for Go

To interact with MongoDB, you need to install the MongoDB driver for Go. Run the following command to install it:

go get go.mongodb.org/mongo-driver/mongo

Connecting to MongoDB

Start by establishing a connection to a MongoDB database. Here's a basic example to connect to a MongoDB instance:

package main

import (
    "context"
    "fmt"
    "log"

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

func main() {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        log.Fatal(err)
    }

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")
}

Creating Documents

Once connected, you can create (or insert) documents in a collection. Here's how you can insert a document:

func insertDocument(client *mongo.Client) {
    collection := client.Database("testdb").Collection("users")
    user := bson.D{
        {"name", "John Doe"},
        {"email", "[email protected]"},
    }

    insertResult, err := collection.InsertOne(context.TODO(), user)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}

Reading Documents

Here's an example of how to query a document:

func readDocument(client *mongo.Client) {
    collection := client.Database("testdb").Collection("users")

    var result bson.M
    filter := bson.D{{"name", "John Doe"}}

    err := collection.FindOne(context.TODO(), filter).Decode(&result)
    if err == mongo.ErrNoDocuments {
        fmt.Println("No document was found with that filter")
        return
    }
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Found a document: ", result)
}

Updating Documents

To update documents, use the following code:

func updateDocument(client *mongo.Client) {
    collection := client.Database("testdb").Collection("users")

    filter := bson.D{{"name", "John Doe"}}
    update := bson.D{{"$set", bson.D{{"email", "[email protected]"}}}}

    updateResult, err := collection.UpdateOne(context.TODO(), filter, update)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Matched %v documents and modified %v documents.", updateResult.MatchedCount, updateResult.ModifiedCount)
}

Deleting Documents

Finally, here’s how you can delete documents:

func deleteDocument(client *mongo.Client) {
    collection := client.Database("testdb").Collection("users")

    filter := bson.D{{"name", "John Doe"}}

    deleteResult, err := collection.DeleteOne(context.TODO(), filter)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Deleted %v documents in the users collection.", deleteResult.DeletedCount)
}

By following this guide, you can effectively perform CRUD operations using Go and MongoDB. Remember to replace "localhost" with your MongoDB URI if you are connecting to a different MongoDB instance in the cloud or another server.