How To Use Golang with MongoDB.

Photo by Boitumelo Phetla on Unsplash

In this article, I will give you an introduction to using Golang with MongoDB. First, I’ll show you how to install MongoDB and important Golang packages.

Then, we’ll connect to a MongoDB server, ping it, and list the existing databases. After that, I’ll go over an example where I use various functions for performing CRUD operations.

Installing MongoDB for your platform is pretty straightforward. You can get the community edition from here.

Given that I’m working on windows, I had the option of installing MongoDB as a service. I choose not to do this because I use MongoDB as a test server. However, the result is that I need to start MongoDB manually.

Manual starting of MongoDB on windows

To start the MongoDB server manually, you can do the following:

  • First, make sure there is a data directory in your path from where you are running the command — in the example below, it’s ./data.
  • Then run "C:Program FilesMongoDBServer5.0binmongod" — dbpath ./data in your terminal. Your path may be slightly different. In this case, you can search for mongod and see what the path may be on your system.

The MongoDB Compass desktop app

You can also install MongoDB Compass. Get it here.

This desktop app can help you manage and audit the data you enter into the MongoDB server.

This is very handy for testing purposes as this app lets you see which databases, collections, and documents have been created.

The server address and password

For the rest of this article, my MongoDB database server will be running at the address mongodb://localhost:27017.

As the database is just for exploring and testing ideas in Golang, I did not put a username and password on the database server.

If you use it for production code, you’ll need to protect your MongoDB server.

Therefore, when using the MongoDB server for production, the address will look different, including a username and password. See the documentation here.

Installing the Golang packages for MongoDB

To use MongoDB with Golang, you’ll likely need to run the following commands in your terminal:

go mod init
go get go.mongodb.org/mongo-driver/mongo
go get go.mongodb.org/mongo-driver/bson

BSON is used for the serialization of data

In the above commands, you can see that we also install BSON. BSON is a serialization format similar to JSON.

From the BSON specification:

BSON [bee · sahn], short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec.

The rest of the specifications can be read here.

We’ll be using it with MongoDB, for saving document data and for creating filters when addressing documents in queries and the likes.

Let’s start by connecting to the MongoDB server.

We can create many different forms of contexts. For this example, I’ll create the most simple context possible, namely context.TODO(). You can read more about contexts here.

As mentioned above, my database server is located at: mongodb://localhost:27017.

Notice that we defer disconnecting the client from the database in line 17. This means that disconnect will happen after the last statement inside the function it is placed in — in this case, it is main().

Go will still execute the deferred Disconnect() function call if any errors happen after a statement.

If I change the port of the MongoDB to an incorrect port number, for example 20000then the MongoDB client will give no error.

Therefore to be sure we have a proper connection, we can also Ping() the database.

The above code will give an error, as my MongoDB server is not running on port 20000 but on port 27017.

If I change the port to the correct port number, the Ping() statement will not give an error, and the program will complete successfully.

It is possible to list the databases present on your MongoDB server. If you just installed the server, there will likely only be a few ‘administrative’ databases.

As soon as you add more databases, you’ll see them in the listing printed by the statement in line 25.

A quick note here: A collection is more commonly referred to as a database table in other database servers.

Let’s first create a database on our MongoDB server called test and then we’ll add a collection to that database called example.

As this is just an example, and we don’t want to keep the database after the program has run, we’ll also drop (delete) the collection. So in line 25, we’ll defer the Drop() function call so that it will be executed after all the other statements in the main() function.

Obviously, if you wish to keep the database collection after the program has been run, you should remove the Drop() statement (ie, remove line 25).

Here we add documents to the collection we just created.

The documents that we insert each contain three fields: someString, someIntegerand someStringSlice.

In lines 1–5, we create a document with three fields, as mentioned above.

In line 6, let’s first insert this item using the InsertOne() function.

In line 10, we can print out the item’s ID in the collection. For this, we can use the InsertedID property of the result returned by the InsertOne() function.

In lines 11–22, two more documents are created.

Then in lines 23 and 27, we’ll insert these two documents using InsertMany() and list those IDs, too, with the InsertedIDs property.

In line 29, we’ll also include the time.Sleep() statement so that we can use MongoDB Compass to check that the item has been inserted correctly into the collection before the collection gets dropped. If you decide to keep the collection after the program has ended, there is no need to keep the sleep statement.

We can query the collection now that we have inserted documents in our MongoDB collection.

In line 1, we’ll use FindOne() to find one document in the collection. For this example, the ID of this document will match the ID of the first document we inserted in the collection.

In line 2, we create a BSON map called exampleResult for holding the decoded result from the query. This decoded result is a document. By using a BSON map, it will be easy to get the values ​​of the fields.

In line 3, the result of the query is decoded using Decode() into exampleResult.

In lines 5–8, we print out the ID and the three fields of the document.

Then, in line 10, a filter is created that filters the documents according to their someInteger field. This field should be larger than 60.

In line 11, we’ll find several documents with this filter.

In line 15, a slice of BSON maps called examplesResult is created to hold the resulting documents.

In line 16, the function All() is used instead of Decode() for extracting the documents into examplesResult.

Subsequently, in lines 20–25, the fields of the documents contained in examplesResult will be printed out.

Here I go over three ways of updating your documents.

In lines 1–7, we update one document with ID r.InsertedID (which is the ID of the first document we inserted into the collection). In this document, the someInteger field is set to 201. For updating a document by ID, we use the function called UpdateByID().

In line 11, we print how many documents have been updated. The number of updated documents is contained in the result and is extracted using ModifiedCount. In this case, it should be 1.

In lines 14–20, we update one document. For updating one document, we use the function called UpdateOne() . Again this document has the ID of r.InsertedID, but it is addressed differently than before. This time, the someString field is set to "The Updated String".

In fact, instead of using the document ID, you could use a different way of finding the document to update. It can be a document that fulfills a particular property. For example, this could be the document that has someInteger equal to 201 .

In lines 27–33, we can see this idea. Here we update all the documents that fulfill a specific property. This property needs someInteger to be above 60 . All documents that satisfy this are updated such that their someInteger field is set to 60 .

As you can see in the above example, when updating, you’ll typically update just one or a few of the fields of documents.

On the other hand, if you wish to update a complete document, you’ll likely be better off using the ReplaceOne() function. You can read more about that function here.

Last but not least, here is a way to delete a document.

Here in line 1, we’ll delete the first document we inserted into our collection using the DeleteOne() function.

In line 6, we’ll print out how many documents were deleted. This value is extracted from the result of DeleteOne() using DeletedCount . This is analogous to the ModifiedCount property when updating documents.

The MongoDB package also contains a function called DeleteMany() for deleting many documents at a time. You can read more about it here.

Below you can find the entire code for this article. All the above code snippets are included.

Leave a Comment