Reacting to Database Changes with MongoDB Change Streams and Go
Rate this quickstart
If you've been keeping up with my getting started with Go and MongoDB tutorial series, you'll remember that we've accomplished quite a bit so far. We've had a look at everything from CRUD interaction with the database to data modeling, and more. To play catch up with everything we've done, you can have a look at the following tutorials in the series:
Before we take a look at the code, let's take a step back and understand what change streams are and why there's often a need for them.
Imagine this scenario, one of many possible:
You have an application that engages with internet of things (IoT) clients. Let's say that this is a geofencing application and the IoT clients are something that can trigger the geofence as they come in and out of range. Rather than having your application constantly run queries to see if the clients are in range, wouldn't it make more sense to watch in real-time and react when it happens?
With MongoDB change streams, you can create a pipeline to watch for changes on a collection level, database level, or deployment level, and write logic within your application to do something as data comes in based on your pipeline.
While there are many possible use-cases for change streams, we're going to continue with the example that we've been using throughout the scope of this getting started series. We're going to continue working with podcast show and podcast episode data.
Let's assume we have the following code to start:
To watch for changes, we can do something like the following:
The above code will watch for any and all changes to documents within the
episodescollection. The result is a cursor that we can iterate over indefinitely for data as it comes in.
We can iterate over the curser and make sense of our data using the following code:
If data were to come in, it might look something like the following:
In the above example, I've done a
Replaceon a particular document in the collection. In addition to information about the data, I also receive the full document that includes the change. The results will vary depending on the
operationTypethat takes place.
We could make some changes like this:
A few things are happening in the above code. We've moved the stream iteration into a separate function to be used in a goroutine. However, running the application would result in it terminating quite quickly because the
mainfunction will terminate not too longer after creating the goroutine. To resolve this, we are making use of a
WaitGroup. In our example, the
mainfunction will wait until the
WaitGroupis empty and the
WaitGrouponly becomes empty when the goroutine terminates.
Making use of the
WaitGroupisn't an absolute requirement as there are other ways to keep the application running while watching for changes. However, given the simplicity of this example, it made sense in order to see any changes in the stream.
To keep the
iterateChangeStreamfunction from running indefinitely, we are creating and passing a context that can be canceled. While we don't demonstrate canceling the function, at least we know it can be done.
In the previous example, the aggregation pipeline that we used was as basic as you can get. In other words, we were looking for any and all changes that were happening to our particular collection. While this might be good in a lot of scenarios, you'll probably get more out of using a better defined aggregation pipeline.
Take the following for example:
In the above example, we're still watching for changes to the
episodescollection. However, this time we're only watching for new documents that have a
durationfield greater than 30. Any other insert or other change stream operation won't be detected.
The results of the above code, when a match is found, might look like the following:
You just saw how to use MongoDB change streams in a Golang application using the MongoDB Go driver. As previously pointed out, change streams make it very easy to react to database, collection, and deployment changes without having to constantly query the cluster. This allows you to efficiently plan out aggregation pipelines to respond to as they happen in real-time.
If you're looking to catch up on the other tutorials in the MongoDB with Go quick start series, you can find them below:
To bring the series to a close, the next tutorial will focus on transactions with the MongoDB Go driver.
Client-Side Field Level Encryption (CSFLE) in MongoDB with Golang
Feb 03, 2023 | 15 min read
How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI
Sep 27, 2023 | 11 min read