How to Query (Single Doc) Data from Mongo with Go
In this tutorial, I will show you the basics of doing a query for a single document in a Mongo database instance with Go code. I will be on local and provide you with all steps.
I am assuming you have Go installed and have successful compiled at least one Go file. This would confirm your environment works. We will be using my Go boierplate code to save time on setting up our code structure. It follows a
handlershandles the inbound request.
modelscontains all structs that represent data.
repositorieshas all methods for interacting with the database.
servicescontains the business logic of the app.
utilshas any helper methods.
Download the Go boilerplate. Please give it a star on Github so I know people are still using and enjoying it. Move the files into your new project root. Open the files up in a text editor.
You need to do one thing for this boilerplate to work. Open
services/user_service.go and within the
IsValidPassword function. You will need to switch the variable to
true. Do NOT use this code in production without fixing it. I leave encryption and password requirements up to you. This will store a plain text password till you add code to
IsValidPassword. For demo and dev purposes, this is fine.
You will need data in your database and checkout the insert tutorial.
As you can imagine, we will be working with the
repositories layer since it works with the database. If we open the
repositories/cars_repository.go file, you can see the
In the code above, we covert the ID from a string to an objectID. We will then set up our filter and delete one document.
In your terminal:
The first step is to run sign up or sign in. I execute my sign up request with Postman. Copy down the
token in the response.
Or you can run this curl command:
Write down the token. Connect to your database and confirm that you have multiple values. Grab the id of one of the cars.
Next, you will submit a GET request using this id.
Or by curl:
And you can see it returns the car based on the ID.
Thanks for reading!