How to Query Data using Regex from Mongo with Go
In this tutorial, I will show you how to query using regex 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, the filter comes from the query. If you open
models/cars.go, you will see:
Let's just quickly go through what's happening. If there is no query parameters, the search should be:
Otherwise, we begin to build AND cases with OR cases within. What I mean by that is take
make for example. It can be an exact match:
Or it can be similar (start with that string):
The pattern is your regex query. In this case, I'm saying if the word starts with it. I did this because car makes are usually only one word. If someone is trying to type
general motors and they get as far as
g. Then it should not return all makes that contain a
volkswagen. The user is probably not searching for
volkswagen by typing in a middle letter.
In terms of the output of this query, it's:
The same search query is true for model. For year, it's fairly binary. Either they have the correct year or the wrong year. If they provide
20, then it can be from 2000 to 2099 (ie. all years).
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.
Next, you will submit a GET request using a few incomplete make or model names.
Or by curl:
And you can see it returns the car based on make. You can do the same with model:
Thanks for reading!