Docs Menu
Docs Home
/ / /
Go Driver

Usage Examples

On this page

  • Overview
  • How to Use the Usage Examples
  • Examples

Usage examples provide convenient starting points for popular MongoDB operations. Each example provides the following:

  • A full Go program that you can run in your own environment

  • The expected result after running the program

These examples use the sample datasets provided by Atlas. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide or you can import the sample dataset into a local MongoDB instance.

Once you import the dataset, you can copy and paste a usage example into your development environment of choice. You can follow the Quick Start to learn more about getting started with the MongoDB Go Driver.

Follow the "Connect to your Cluster" step to find the connection string to define your MONGODB_URI environment variable to run the usage examples. If your instance uses SCRAM authentication, you can replace <user> with your username, <password> with your password, and <cluster-url> with the URL or IP address of your instance.

To learn more about connecting to your MongoDB instance, see Connection Guide.

To connect the example to your MongoDB instance, you must define an environment variable by using your connection string.

uri := os.Getenv("MONGODB_URI")

You can use GoDotEnv to define your environment variable.

Add the following application configuration in your .env file at the root of your project, replacing the placeholders with the values for your deployment's connection string. To learn more, see the GoDotEnv documentation.

MONGODB_URI=mongodb+srv://<db_username>:<db_password>@<cluster-url>?retryWrites=true&w=majority

You can find usage examples for the following tasks:

Back

What's New