Sling Academy
Home/Golang/Using Go with MongoDB: CRUD example

Using Go with MongoDB: CRUD example

Last updated: November 28, 2024

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.

Next Article: How to redirect in Go (301, 302, etc)

Previous Article: Relative imports in Go: Tutorial & Examples

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant
  • Fixing Go error: syntax error: unexpected X, expecting Y