This tutorial introduces the basic operations of MongoDB from the perspective of the Golang language.
Note: This tutorial uses the official Go language driver package provided by MongoDB.
Prerequisite Tutorials
Note: If you are not familiar with MongoDB, please study the MongoDB knowledge first. The Golang tutorial will not repeat the relevant knowledge.
Basic Requirements
- Go 1.10 or higher
- MongoDB 2.6 or higher
Install Dependencies
go get go.mongodb.org/mongo-driver/mongo
Connect to MongoDB
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
// MongoDB connection address
uri := "mongodb://localhost:27017"
// Get the context object, you can set a timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Connect to MongoDB
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
The Connect function does not block the goroutine. That is to say, directly operating MongoDB after calling the Connect method may result in an error because MongoDB has not connected successfully. You can use the Ping method to check if MongoDB has connected successfully.
// Ping MongoDB, if connected successfully, no error is returned
err = client.Ping(ctx, readpref.Primary())
MongoDB Connection Address
The MongoDB connection address includes important information such as the server address, port number, account, and password.
The format is as follows:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
Example:
// Connect to the localhost:27017 address with the default username and password
mongodb://localhost:27017
// Connect to the localhost:27017 address with the account=root, password=123456, and connect to the default database=admin
mongodb://root:123456@localhost:27017/admin
Release Connection Resources
If the connection is no longer needed, you need to manually release the connection resources.
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
Get Collection Instance
To operate MongoDB in Golang, you need to get the collection instance first, and then you can perform CRUD operations on the collection instance.
// Set the database name through Database, and set the collection name through Collection
collection := client.Database("testing").Collection("numbers")
Note: According to the characteristics of MongoDB, it is not necessary to create the database and collection in advance. They will be created automatically when data is first written.
Insert Document
Insert data using the InsertOne function.
// Context object, commonly used to set the request timeout, you can also reuse the context object created earlier, no need to redefine it
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Insert document, here we use the bson.D type to describe the JSON document, bson.D represents a JSON array
res, err := collection.InsertOne(ctx, bson.D{{"name", "pi"}, {"value", 3.14159}})
// Get the id of the newly added document
id := res.InsertedID
You need to import the following packages:
import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
Note: In Golang, the bson package is used to represent the JSON document data structure. The following chapters will detail the expression of MongoDB data storage structures in Golang.
```go
package main
import (
“context”
“fmt”
“time”
“go.mongodb.org/mongo-driver/bson”
“go.mongodb.org/mongo-driver/mongo”
“go.mongodb.org/mongo-driver/mongo/options”
“go.mongodb.org/mongo-driver/mongo/readpref”
)
func main() {
// Set MongoDB connection address
uri := “mongodb://root:123456@localhost:27017/admin”
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Connect to MongoDB
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
// Release the connection with delay
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
// Check if MongoDB connection is successful
if err := client.Ping(ctx, readpref.Primary()); err != nil {
panic(err)
}
fmt.Println("MongoDB connected successfully!")
// Get the numbers collection
collection := client.Database("testing").Collection("numbers")
// Insert a document
res, err := collection.InsertOne(ctx, bson.D{{"name", "pi"}, {"value", 3.14159}})
id := res.InsertedID
fmt.Println("New document Id=", id)
}
```