Table of Contents
Installing the Go driver for MongoDB
MongoDB CRUD operations
Read a document in MongoDB
Create a document in MongoDB
Update a document in MongoDB
Delete a document in MongoDB
Conclusion
Home System Tutorial MAC How to use Go with MongoDB

How to use Go with MongoDB

Apr 12, 2025 am 09:27 AM

How to use Go with MongoDB

MongoDB is a document-oriented NoSQL database. If you want to use it in your Golang projects, good news — MongoDB does support Golang! Follow this tutorial on connecting Go and MongoDB and developing projects involving both.

In the below article, we describe exactly how to set up your MongoBD as a datasource in Go. Plus, we show how to run some of the basic CRUD operations in the database.

To follow the steps of this Golang — MongoDB tutorial, you’ll need Go installed on your Mac, so make sure you have it before we begin.

Installing the Go driver for MongoDB

In order to use MongoDB with Go, you need a respective driver. Luckily, MongoDB provides official documentation for the process. Let’s go through all the steps together.

Disclaimer: In this post, we are only covering the Go driver, for other MongoDB drivers, check the official documentation.

To get started with MongoDB in Go, initialize your project with go mod in a new directory. Here are the terminal commands for that:

mkdir go-quickstart
cd go-quickstart
go mod init go-quickstart
Copy after login

Next, add MongoDB dependency with go get command:

go get go.mongodb.org/mongo-driver/mongo
Copy after login

Now you are ready to create a database cluster in your MongoDB account. To do that, you’ll need to join MongoDB Atlas. It’s a great solution for getting your feet wet with MongoDB in Golang since it has a free tier and is hosted in the cloud.

What you need to do to connect your MongoDB Golang driver is create an Atlas account (you can just sign in through your Google account), deploy a free cluster, add your IP to the allowed connections list, create a database user for the cluster you’ve deployed, connect to the cluster, and begin working with your data.

How to use Go with MongoDB

Go through these steps starting with the registration at https://account.mongodb.com/account/register. If you encounter any hiccups, here’s an official guide to each of the steps.

None of these require code and you should be able to complete the actions in the Atlas interface. Once you complete this step, we can continue with our setup for connecting to your MongoDB database cluster with the help of the MongoDB Go Driver.

Note that when you are connecting to your cluster, you need to select Connect to your application, and then on the next page, copy the connection string to add to your application code:

How to use Go with MongoDB

Copy your snippet to use later in your code editor. We like to save our code bits in SnippetsLab, a dedicated app to host a library of your code snippets.

How to use Go with MongoDB

Remember to replace and in the snippet with your database password that you’ve created at registration in Atlas. We recommend saving your login credentials in a safe location.

We used app Secrets to save our MongoDB cluster login credentials:

How to use Go with MongoDB

Now, create and save the file containing your application into your go-quickstart folder (you can use a different name for your project folder, but make sure you make respective changes in the code we provided in the earlier steps).

We are developing this project in CodeRunner, an app that allows you to save, edit, and run your code in more than 25 languages, including Go. So to write our program, we created the main.go in CodeRunner using MongoDB’s sample code from this official tutorial and put the file in our root folder for the project /go-quickstart.

How to use Go with MongoDB

Here’s the code we used:

package main
import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"
    "github.com/joho/godotenv"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
    if err := godotenv.Load(); err != nil {
        log.Println("No .env file found")
    }
    uri := os.Getenv("MONGODB_URI")
    if uri == "" {
        log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/#environment-variable")
    }
    client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
    if err != nil {
        panic(err)
}
    defer func() {
        if err := client.Disconnect(context.TODO()); err != nil {
            panic(err)
    }
}()
    coll := client.Database("sample_mflix").Collection("movies")
    title := "Back to the Future"
    var result bson.M
    err = coll.FindOne(context.TODO(), bson.D{{"title", title}}).Decode(&result)
    if err == mongo.ErrNoDocuments {
        fmt.Printf("No document was found with the title %s\n", title)
        return
    }
    if err != nil {
        panic(err)
    }
    jsonData, err := json.MarshalIndent(result, "", "    ")
    if err != nil {
        panic(err)
    }
    fmt.Printf("%s\n", jsonData)
}
Copy after login

Now, in order to successfully run this code, you also need an .env file in your app’s root folder (/go-quickstart in our example).

To create an empty .env file, we used this Terminal command:

touch .env
Copy after login

Next, we added our connection string into the .env file with a series of Terminal commands:

  1. Execute vim .env in Terminal.
  2. Set the value for MONGODB_URI with:
    MONGODB_URI="mongodb srv://<username>:<password>@cluster0.icb48.mongodb.net/myFirstDatabase?retryWrites=true&w=majority</password></username>
    Copy after login
    Copy after login
  3. Execute :wq! command.
  4. Execute cat .env in Terminal to check your changes have been saved correctly. Your .env file should read:
    MONGODB_URI="mongodb srv://<username>:<password>@cluster0.icb48.mongodb.net/myFirstDatabase?retryWrites=true&w=majority</password></username>
    Copy after login
    Copy after login

Now you are ready to do your MongoDB database ping with command:

go run main.go
Copy after login

If you’ve loaded your sample database as directed in the steps to your Atlas account setup, you should get a response containing information from that sample database.

In our example, we got info from our MongoDB library on a Hollywood movie:

How to use Go with MongoDB

MongoDB CRUD operations

To perform CRUD operations in MongoDB, you need to import the BSON package. Since its import is included in the code we’ve used for our Go program sample above (from the MongoDB official tutorial), you don’t have to do it manually.

But if you are writing your own thing, the line for import is:

"go.mongodb.org/mongo-driver/bson"
Copy after login

Now, let’s read some data in your sample MongoBD database.

Read a document in MongoDB

Here’s the code you need to add to main.go to make a request for information about The Room movie:

coll := client.Database("sample_mflix").Collection("movies")
var result bson.M
err = coll.FindOne(context.TODO(), bson.D{{"title", "The Room"}}).Decode(&result)
if err != nil {
    if err == mongo.ErrNoDocuments {
        // This error means your query did not match any documents.
        return
    }
    panic(err)
}
Copy after login

You can also copy the full code for your sample main.go file in the official MongoDB tutorial here.

Next, let’s move to writing operations.

Create a document in MongoDB

Add a document to your collection with this code:

coll := client.Database("insertDB").Collection("movies")
doc := bson.D{{"title", "Sunny Days and Nights in 1672"}, {"text", "This is just a test"}}
result, err := coll.InsertOne(context.TODO(), doc)
if err != nil {
    panic(err)
}
Copy after login

Full sample code available in the official MongoDB tutorial on this page.

Run your code and get a confirmation your document has been inserted:

How to use Go with MongoDB

To check, run the find query. You should get your sample info back:

How to use Go with MongoDB

Read also:

  • Use Go With Mysql
  • Use Redis As Database
  • Best Developer Tools for Mac
  • Git Client Mac

Update a document in MongoDB

Now, you can introduce changes to your database record. To do that, use the update tool.

Here’s a sample code for that:

coll := client.Database("insertDB").Collection("movies")
id, _ := primitive.ObjectIDFromHex("6205210bc9748a7cee6af8cb")
filter := bson.D{{"_id", id}}
update := bson.D{{"$set", bson.D{{"average_rtng", 4.5}}}}
result, err := coll.UpdateOne(context.TODO(), filter, update)
if err != nil {
    panic(err)
}
Copy after login

Your result after running your updated program code should read: Documents updated: 1

Run a find query to test it. Here is what your results can look like (note that we ran quite a few updates to recheck the code, so our results contain a bit more info than with just the above update):

How to use Go with MongoDB

Delete a document in MongoDB

And finally, let’s see how we can delete documents from our MongoDB database.

This code will delete the first matched title in your collection:

coll := client.Database("insertDB").Collection("movies")
filter := bson.D{{"title", "Your Newly Updated Title"}}
result, err := coll.DeleteOne(context.TODO(), filter)
if err != nil {
    panic(err)
}
Copy after login

How to use Go with MongoDB

Conclusion

As you can see, setting up your MongoDB database to work with Golang only takes a few lines of code. We hope this tutorial was helpful in your journey to mastering Golang and MongoDB databases. Go and MongoDB work great together and can be your handy helpers in numerous projects, so we expect you’ve been able to figure out how to use MongoDB with the help of this guide.

Note that MongoDB Atlas only allows you to create one free cluster, and you’ll have to pay for any additional ones.

For our project, we also used three additional apps — CodeRunner, SnippetsLab, and Secrets. You can find them all in Setapp, a curated innovative service of tools for daily productivity and automating routine tasks.

Discover tools for coding, cleaning up your Mac, backing up files, and more on Setapp. Begin with a 7-day free trial right now and try CodeRunner, SnippetsLab, Secrets, and dozens more tools right away.

The above is the detailed content of How to use Go with MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spotify on Apple Watch: How to use it in 2025 Spotify on Apple Watch: How to use it in 2025 Apr 04, 2025 am 09:55 AM

With the support of Apple devices' interconnected ecosystem, managing and synchronizing your Apple devices has become a breeze. Unlock Mac with Apple Watch? Simple! (If you haven't set this unlocking method yet, you should really try it, it's very time-saving). Can you pay with Apple Watch without using iPhone? Apple can handle it easily! Today we will focus on how to download the Spotify playlist to an Apple Watch and play without an iPhone. Spoiler: This is possible. How to use Spotify on Apple Watch: A quick overview Let's dive into the key issues and their solutions directly. If this form helps you, that would be great! If you

How to get rid of 'Your screen is being observed' error How to get rid of 'Your screen is being observed' error Apr 05, 2025 am 10:19 AM

When you see the message "Your screen is being monitored", the first thing you think of is someone hacking into your computer. But that's not always the case. Let's try to find out if there are any issues that need you to worry about. Protect your Mac With Setapp, you don't need to worry about choosing a tool to protect your computer. You can quickly form your own suite of privacy and security software on Setapp. Free Trial Security Test What does "Your screen is being monitored" mean? There are many reasons why there is a Mac lock screen message that appears with “Your screen is being monitored”. You are sharing the screen with others You are recording the screen You are using AirPlay You are using some apps that try to access your screen Your computer is infected with evil

Email is not syncing? How to refresh the Mail app on Mac Email is not syncing? How to refresh the Mail app on Mac Apr 04, 2025 am 09:45 AM

Mac mail synchronization failed? Quick solution! Many Mac users rely on the included Mail app because it is simple and convenient. But even reliable software can have problems. One of the most common problems is that Mail cannot be synced, resulting in recent emails not being displayed. This article will guide you through email synchronization issues and provide some practical tips to prevent such issues. How to refresh the Mail app on your Mac Operation steps Click the envelope icon Open the Mail app > View > Show Tab Bar > Click the Envelope icon to refresh. Use shortcut keys or menu options Press Shift Command N. Or open the Mail app

How to uninstall Honey from Mac How to uninstall Honey from Mac Apr 04, 2025 am 10:13 AM

How to show only active apps in Dock on Mac How to show only active apps in Dock on Mac Apr 09, 2025 am 11:44 AM

Mac Dockbar Optimization Guide: Show only running applications The dock bar of your Mac is the core of the system, from which you can launch Finder, Trash, recently used apps, active apps, and bookmark apps, and even add folders such as Document and Downloads. By default, the Mac dock bar will display more than a dozen Apple-owned applications. Most users will add more applications, but rarely delete any applications, resulting in the dock bar being cluttered and difficult to use effectively. This article will introduce several ways to help you organize and clean up your Mac dock bar in just a few minutes. Method 1: Manually organize the dock bar You can manually remove unused applications and keep only commonly used applications. Remove the application: Right-click on the application

Mac Keyboard Volume Buttons not Working: Here Is How to Fix These Keys Mac Keyboard Volume Buttons not Working: Here Is How to Fix These Keys Apr 02, 2025 am 09:33 AM

Mac volume key fails? Quick Repair Guide! Mac volume keys are not working properly? Whether it’s enjoying music, watching movies or having important video calls, it’s very frustrating. Don't worry, this article provides effective solutions to help you quickly restore audio control. Reasons for Mac volume key failure: Volume key failure is usually not a hardware failure, but a software setup or failure. Common reasons include: Audio driver failure Keyboard settings change External speaker control Other software interference Most of the problems can be easily solved. How to fix the volume key failure of Mac keyboard: The following methods will help you solve the volume key problem: Check keyboard settings: The volume key failure may be related to the keyboard settings. Click on the Apple menu

See all articles