How To Filter In Mongodb Golang
In the first tutorial, which tin can best exist named a Quick First into MongoDB evolution with the Get programming linguistic communication (Golang), we're going to be exploring how to institute connections betwixt the language and the database.
When information technology comes to futurity tutorials in the series, look content on the following:
- Database create, recollect, update, and delete (CRUD) operations.
- A look into MongoDB aggregation queries.
- Watching change streams in MongoDB.
- Multi-Document ACID transactions.
Get is i of the more than recent of the officially supported technologies with MongoDB, and in my personal opinion, it is ane of the most awesome!
Throughout these tutorials, I'll be using Visual Studio Code (VS Lawmaking) for development, and I'll be connecting to a MongoDB Atlas cluster. The assumption is that yous're using Go 1.xiii or newer and that it is already properly installed and configured on your calculator. It is also causeless that an Atlas cluster has already been created.
MongoDB Atlas offers a forever Gratis tier that can be accessed within the MongoDB Cloud.
If you're using a different IDE, O/Southward, etc., the walk-through might be slightly different, only the code will exist pretty much the same.
Getting Started
Create a new project directory titled quickstart
, and add a main.go
file to that projection.
For this particular tutorial, all lawmaking will be added to the main.get
file. Nosotros tin can offset the main.become
file with the post-obit boilerplate lawmaking, necessary for our dependency director:
package master func primary() { }
The next stride is to install the MongoDB Become Driver using Go modules. To do this, execute the following from the command line:
$ get mod init quickstart $ get go go.mongodb.org/mongo-driver
Notation that for this tutorial nosotros are using Get modules to manage our packages. This requires Get version 1.xi or higher. If using Go 1.11, this requires the quickstart
module to be created outside $GOPATH/src
if you also take a $GOPATH set upward. For more than information about Go modules, see https://blog.golang.org/using-go-modules.
With the driver installed, open the project's main.get
file, and add the following imports to the code:
parcel main import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-commuter/bson" "get.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-commuter/mongo/options" "go.mongodb.org/mongo-commuter/mongo/readpref" ) func main() { }
The to a higher place code represents the imported modules within the MongoDB Go Driver that will exist used throughout the tutorial serial. Almost logic, at to the lowest degree for at present, volition exist in the main
function.
Inside the main
function, let's found a connectedness to our MongoDB Atlas cluster:
func chief() { client, err := mongo.NewClient(options.Client().ApplyURI("<ATLAS_URI_HERE>")) if err != nil { log.Fatal(err) } ctx, _ := context.WithTimeout(context.Background(), 10*time.2nd) err = client.Connect(ctx) if err != zilch { log.Fatal(err) } defer client.Disconnect(ctx) }
There are a few things that are happening in the higher up code. First we're configuring our client to use the correct URI, but nosotros're not yet connecting to it. Assuming goose egg is malformed and no error was thrown, we tin ascertain a timeout duration that we desire to use when trying to connect. The ten seconds I used might exist a footling too generous for your needs, but feel free to play effectually with the value that makes the almost sense to you.
In regards to the Atlas URI, you lot can employ any of the driver URIs from the Atlas dashboard. They'll look something like this:
mongodb+srv://<username>:<password>@cluster0-zzart.mongodb.net/test?retryWrites=true&w=bulk
Just remember to utilise the data that Atlas provides for your particular cluster.
After connecting, if there isn't an fault, nosotros can defer the endmost of the connection for when the principal
function exits. This volition keep the connection to the database open until we're done.
So if no errors were thrown, tin nosotros be sure that we're actually connected? If you're concerned, we can ping the cluster from inside our application:
err = client.Ping(ctx, readpref.Primary()) if err != nada { log.Fatal(err) }
The in a higher place code uses our connected customer and the context that we had previously defined. If at that place is no fault, the ping was a success!
We tin can take things a footstep further by list the available databases on our MongoDB Atlas cluster. Inside the main
function, add the following:
databases, err := customer.ListDatabaseNames(ctx, bson.M{}) if err != nil { log.Fatal(err) } fmt.Println(databases)
The above code will return a []string
with each of the database names. Since we don't plan to filter whatever of the databases in the list, the filter
argument on the ListDatabaseNames
function can be bson.Grand{}
.
The result of the in a higher place lawmaking might be something like this:
[quickstart video admin local]
Of course, your actual databases will probable be different than mine. It is non a requirement to have specific databases or collections at this stage of the tutorial.
To bring everything together, take a look at our project thus far:
package main import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-driver/bson" "get.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" ) func main() { customer, err := mongo.NewClient(options.Customer().ApplyURI("<ATLAS_URI_HERE>")) if err != nil { log.Fatal(err) } ctx, _ := context.WithTimeout(context.Groundwork(), 10*fourth dimension.Second) err = customer.Connect(ctx) if err != nil { log.Fatal(err) } defer client.Disconnect(ctx) err = customer.Ping(ctx, readpref.Principal()) if err != nil { log.Fatal(err) } databases, err := client.ListDatabaseNames(ctx, bson.M{}) if err != naught { log.Fatal(err) } fmt.Println(databases) }
Not bad for 34 lines of code, considering that about half of that was simply defining the imports for packages to be used within the project.
Conclusion
You merely saw how to connect to a MongoDB Atlas cluster with the Go programming language. If you decide not to utilize Atlas, the code will nonetheless work, you lot'll just accept a dissimilar connectedness string.
Become is a powerful technology and combined with MongoDB you tin can accomplish anything from web applications to desktop applications.
Stay tuned for the next tutorial in the serial which focuses on Grime operations against MongoDB using Golang.
Take a look at a video of this in action below.
How To Filter In Mongodb Golang,
Source: https://www.mongodb.com/blog/post/quick-start-golang-mongodb-starting-and-setup
Posted by: thralltivent.blogspot.com
0 Response to "How To Filter In Mongodb Golang"
Post a Comment