Steps to operate an MongoDB database using golang drivers

  • 2021-01-06 00:49:04
  • OfStack

Install the MongoDB driver


mkdr mongodb 
cd mongodb 
go mod init 
go get go.mongodb.org/mongo-driver/mongo

Connection MongoDB

Create a file main.go

Import the following package into the file main.go


package main

import (
 "context"
 "fmt"
 "log"
 "go.mongodb.org/mongo-driver/bson"
 "go.mongodb.org/mongo-driver/mongo"
 "go.mongodb.org/mongo-driver/mongo/options"
 "time"
)

The URI format for connecting to MongoDB is


mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

Stand-alone version


mongodb://localhost:27017

A copy of the set


mongodb://mongodb0.example.com:27017,mongodb1.example.com : 27017 . mongodb2.example.com : 27017 /?replicaSet = myRepl

Shard cluster


mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017

mongo.Connect () accepts Context and options.ClientOptions objects, which are used to set connection strings and other driver Settings.
context.TODO () indicates that it is not sure which context is being used now, but one will be added in the future

Use the Ping method to verify that MongoDB is properly connected


func main() {
 clientOptions := options.Client().ApplyURI("mongodb://admin:password@localhost:27017")
 var ctx = context.TODO()
 // Connect to MongoDB
 client, err := mongo.Connect(ctx, clientOptions)
 if err != nil {
 log.Fatal(err)
 }
 // Check the connection
 err = client.Ping(ctx, nil)
 if err != nil {
 log.Fatal(err)
 }
 fmt.Println("Connected to MongoDB!")
 defer client.Disconnect(ctx)

List all databases


databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
 log.Fatal(err)
}
fmt.Println(databases)

BSON objects are used in GO

JSON documents in MongoDB are stored in a binary representation called BSON (JSON for binary encoding). Unlike other databases that store JSON data as simple strings and numbers, the BSON encoding extends the JSON representation, such as int, long, date, float, point, and decimal128. This makes it easier for applications to reliably process, sort, and compare data. Go There are two series of Driver used to represent BSON data: D series types and Raw series types.

The D series includes 4 types:

D: BSON documentation. This type is used in situations where order is important, such as the MongoDB command. M: Unordered map. Same as D except that the order is not reserved. A: An array of BSON. E: A single element in D.

Insert data into MongoDB

Insert a single document


// Define the structure of the inserted data 
type sunshareboy struct {
Name string
Age int
City string
}
// Connect to the test The library sunshare A collection of , Collections are created automatically when they do not exist 
collection := client.Database("test").Collection("sunshare")
wanger:=sunshareboy{"wanger",24," Beijing "}
insertOne,err :=collection.InsertOne(ctx,wanger)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a Single Document: ", insertOne.InsertedID)

The execution results are as follows

[

![](https://s4.51cto.com/images/blog/202011/07/378adacb26314b3532fa8947e3516fc1.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
#### to insert multiple documents simultaneously
```go
collection := client.Database("test").Collection("sunshare")

:=
{
{
{
{
{
};
huazai:= huazai {huazai {huazai {huazai {huazai};
sunshareboy :=sunshareboy{sunshareboy{sunshareboy{sunshareboy{sunshareboy{sunshareboy{sunshareboy{sunshareboy};
god:= god {god {god}}
qiaoke:=sunshareboy{qiaoke {qiaoke {qiaoke};
jiang:= jiang {jiang {jiang {jiang};
// Insert multiple pieces of data using slices
boys:=[]interface{}{dongdong,huazai,suxin,god,qiaoke,jiang}
insertMany,err:= collection.InsertMany(ctx,boys)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertMany.InsertedIDs)

]

Query data from MongDB

Query a single document

Querying a single document using the collection.FindOne () function requires an filter document and a pointer that can decode the result into its value


var result sunshareboy
filter := bson.D{{"name","wanger"}}
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
 log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)

The results are as follows

[

Connected to MongoDB!
Found a single document: {Name:wanger Age:24 City: Beijing}
Connection to MongoDB closed.

]

Query multiple documents

Use the function collection.Find () to query multiple documents. This function returns a cursor that can be used to iterate over and decode the document. When the iteration is complete, the cursor is closed

The Find function executes the find command and returns Cursor on the matching documents in the collection. The filter parameter must be a document that contains the query operator and can be used to select which documents to include in the result. It can't be zero. An empty document (for example, bson.D {}) is applied to contain all documents. opts parameters can be used to specify the operating options, for example, we can set the return only 5 of the document limit (https: / / godoc. org/go. mongodb. org/mongo - driver mongo/options # Find).

package main

import (
 "context"
 "fmt"
 "log"
 "go.mongodb.org/mongo-driver/bson"
 "go.mongodb.org/mongo-driver/mongo"
 "go.mongodb.org/mongo-driver/mongo/options"
 "time"
)

0

The results are as follows

[

Connected to MongoDB!
{wanger 24 Beijing}
{Zhang Dongdong 29 Chengdu}
{Wai 28 Shenzhen}
{Suxin 24 Gansu}
{Liu Daxian 24 Hangzhou}
Found multiple documents (array of pointers): & [0xc000266450 0xc000266510 0xc000266570 0xc0002665d0 0xc000266630]
Connection to MongoDB closed.

]

Update MongoDB documentation

Update a single document

Using the collection.UpdateOne () function, one filter is needed to match the documents in the database, and one update document is needed to update the operation

The filter parameter must be a document that contains the query operator and can be used to select the document to update. It can't be zero. If the filter does not match any documents, the operation will succeed and UpdateResult with MatchCount of 0 will be returned. If the filter matches multiple documents, 1 is selected from the matching set, and MatchedCount is equal to 1. update parameters must be contained document update operators (https: / / docs. mongodb. com manual/reference operator/update /), and can be used to specify the changes to the selected document. It cannot be nil or empty. The opts parameter can be used to specify options for an operation.

package main

import (
 "context"
 "fmt"
 "log"
 "go.mongodb.org/mongo-driver/bson"
 "go.mongodb.org/mongo-driver/mongo"
 "go.mongodb.org/mongo-driver/mongo/options"
 "time"
)

1

The results are as follows

[

Connected to MongoDB!
Matched 1 documents and updated 1 documents.
Connection to MongoDB closed.

]

Update multiple documents

Update multiple documents using the collection.UpdateOne () function with the same parameters as the collection.UpdateOne () function


package main

import (
 "context"
 "fmt"
 "log"
 "go.mongodb.org/mongo-driver/bson"
 "go.mongodb.org/mongo-driver/mongo"
 "go.mongodb.org/mongo-driver/mongo/options"
 "time"
)

2

The results are as follows

[

Connected to MongoDB!
Matched 2 documents and updated 2 documents.
Connection to MongoDB closed.

]

Delete the MongoDB document

Documents can be deleted using collection.DeleteOne () or collection.DeleteMany (). If you pass bson.D {{}} as a filter parameter, it will match all documents in the dataset. You can also delete the entire dataset using collection.drop ().


filter := bson.D{{"city"," tieling "}}
deleteResult, err := collection.DeleteMany(context.TODO(), filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)

The results are as follows

[

Connected to MongoDB!
Deleted 2 documents in the trainers collection
Connection to MongoDB closed.

]

Gets MongoDB service status

We introduced above to MongoDB CRUD, actually also supports many for mongoDB operations, such as polymerization, things, etc., then introduce 1 use golang get MongoDB service status, execution will return after 1 bson. Raw types of data


package main

import (
 "context"
 "fmt"
 "log"
 "go.mongodb.org/mongo-driver/bson"
 "go.mongodb.org/mongo-driver/mongo"
 "go.mongodb.org/mongo-driver/mongo/options"
 "time"
)

4

Refer to the link

https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial https://godoc.org/go.mongodb.org/mongo-driver/mongo

Related articles: