Go Mongo!!
Season-01 Episode-01 ( The one with the basics)
While writing this blog the world is going through a difficult time (COVID-19). Please Stay Safe. Stay Inside and Learn new stuff.
We will be using a mongo-go-driver driver to learn certain operations.
What is required?
- Go 1.10 or higher.
- MongoDB 2.6 and higher.
How do I install?
The best way to get started using the MongoDB Go driver is by using go modules to install the dependency in your project. which can be achieved either by importing packages from go.mongodb.org/mongo-driver
or by directly running
go get go.mongodb.org/mongo-driver/mongo
How do I use?
To get started with the driver, import the mongo
package, create a mongo.Client
:
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
And connect it to your running MongoDB server:
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
To do this in a single step, you can use the Connect
function:
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
Calling Connect
does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to, use the Ping
method:
ctx, _ = context.WithTimeout(context.Background(), 2*time.Second)
err = client.Ping(ctx, readpref.Primary())
To insert a document into a collection, first retrieve a Database
and then Collection
instance from the Client
:
collection := client.Database("learning").Collection("numbers")
The Collection
instance can then be used to insert documents:
ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
res, err := collection.InsertOne(ctx, bson.M{"name": "Pi", "Data": 3.14159})
id := res.InsertedID
Several query methods return a cursor, which can be used like this:
ctx, _ = context.WithTimeout(context.Background(), 50*time.Second)
cur, err := collection.Find(ctx, bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(ctx)
for cur.Next(ctx) {
var result bson.M
err := cur.Decode(&result)
if err != nil { log.Fatal(err) }
// your code
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
For methods that return a single item, a SingleResult
instance is returned:
var result struct {
Data float64
}
filter := bson.M{"name": "pi"}
ctx, _ = context.WithTimeout(context.Background(), 5*time.Second)
err = collection.FindOne(ctx, filter).Decode(&result)
if err != nil {
log.Fatal(err)
}