Use golang driver to operate MongoDB database

Install MongoDB driver

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

Connect to MongoDB

Create a main.go file and
import the following packages into the main.go file

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]]

single vision

mongodb://localhost:27017

Replica set

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

Sharded 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 the connection string and other driver settings.
By context.TODO()expressing that you are not sure which context to use now, but will add a
Ping method in the future to detect whether MongoDB has been connected normally

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)

Use BSON objects in GO

JSON documents in MongoDB are stored in a binary representation called BSON (Binary Encoded JSON). Unlike other databases that store JSON data as simple strings and numbers, 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 Driver has two series for representing BSON data: D series type and Raw系列type.
DThe series includes four types:

  • D: BSON document. This type is used in scenarios where order is important, such as MongoDB commands.
  • M: Unordered map. DSame as except that the order is not preserved .
  • A: A BSON array.
  • E: DA single element in.

    Insert data into MongoDB

    Insert a single document

    
    //定义插入数据的结构体
    type sunshareboy struct {
    Name string
    Age  int
    City string
    }

//Connect to the sunshare collection of the test library. If the collection does not exist, the collection will be created automatically
:= 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)

执行结果如下  
![](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=)
#### 同时插入多条文档
```go
collection := client.Database("test").Collection("sunshare")
dongdong:=sunshareboy{"张冬冬",29,"成都"}
huazai:=sunshareboy{"华仔",28,"深圳"}
suxin:=sunshareboy{"素心",24,"甘肃"}
god:=sunshareboy{"刘大仙",24,"杭州"}
qiaoke:=sunshareboy{"乔克",29,"重庆"}
jiang:=sunshareboy{"姜总",24,"上海"}
//插入多条数据要用到切片
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

To query a single document, use the collection.FindOne() function, which requires a filter document and a pointer that can decode the result to 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 returned result is as follows

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

Query multiple documents

To query multiple documents, use the collection.Find() function. This function returns a cursor, which can be used to iterate and decode the documents. When the iteration is completed, close the cursor

  • The Find function executes the find command and returns Cursor on the matching documents in the collection.
  • The filter parameter must be the document containing the query operator and can be used to select which documents are included in the result. It cannot be zero. Empty documents (such as bson.D {}) should be used to include all documents.
  • The opts parameter can be used to specify the options of the operation. For example, we can set the limit of returning only five documents (https://godoc.org/go.mongodb.org/mongo-driver/mongo/options#Find)。

    //定义返回文档数量
    findOptions := options.Find()
    findOptions.SetLimit(5)
    
    //定义一个切片存储结果
    var results []*sunshareboy
    
    //将bson.D{{}}作为一个filter来匹配所有文档
    cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
    if err != nil {
        log.Fatal(err)
    }
    //查找多个文档返回一个游标
    //遍历游标一次解码一个游标
    for cur.Next(context.TODO()) {
        //定义一个文档,将单个文档解码为result
        var result sunshareboy
        err := cur.Decode(&result)
        if err != nil {
            log.Fatal(err)
        }
        results = append(results, &result)
    }
    fmt.Println(result)
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }
    //遍历结束后关闭游标
    cur.Close(context.TODO())
    fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)

    The returned result is as follows

    Connected to MongoDB!
    {wanger 24 北京}
    {张冬冬 29 成都}
    {华仔 28 深圳}
    {素心 24 甘肃}
    {刘大仙 24 杭州}
    Found multiple documents (array of pointers): &[0xc000266450 0xc000266510 0xc000266570 0xc0002665d0 0xc000266630]
    Connection to MongoDB closed.

    Update MongoDB documentation

    Update a single document

    To update a single document, use the collection.UpdateOne() function, a filter is needed to match the document in the database, and an update document is also needed to update the operation

  • The filter parameter must be the document containing the query operator, and can be used to select the document to be updated. It cannot be zero. If the filter does not match any documents, the operation will succeed and an UpdateResult with a MatchCount of 0 will be returned. If the filter matches multiple documents, one will be selected from the matched set, and MatchedCount is equal to 1.
  • The update parameter must be a document containing the update operator (https://docs.mongodb.com/manual/reference/operator/update/ ), and can be used to specify modifications to the selected document. It cannot be nil or empty.
  • The opts parameter can be used to specify options for the operation.
    filter := bson.D{{"name","张冬冬"}}
    //如果过滤的文档不存在,则插入新的文档
    opts := options.Update().SetUpsert(true)
    update := bson.D{
    {"$set", bson.D{
        {"city", "北京"}},
    }}
    result, err := collection.UpdateOne(context.TODO(), filter, update,opts)
    if err != nil {
    log.Fatal(err)
    }
    if result.MatchedCount != 0 {
    fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
    }
    if result.UpsertedCount != 0 {
    fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID)
    }

    The returned result is as follows

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

    Update multiple documents

    To update multiple documents, use the collection.UpdateOne() function with the same parameters as the collection.UpdateOne() function

    filter := bson.D{{"city","北京"}}
    //如果过滤的文档不存在,则插入新的文档
    opts := options.Update().SetUpsert(true)
    update := bson.D{
    {"$set", bson.D{
        {"city", "铁岭"}},
    }}
    result, err := collection.UpdateMany(context.TODO(), filter, update,opts)
    if err != nil {
    log.Fatal(err)
    }
    if result.MatchedCount != 0 {
    fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
    }
    if result.UpsertedCount != 0 {
    fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID)
    }

    The returned result is as follows

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

    Delete MongoDB documents

    You can use collection.DeleteOne()or collection.DeleteMany()delete the document. If you pass it bson.D{{}}as a filter parameter, it will match all documents in the dataset. You can also use to collection. drop()delete the entire data set.

    filter := bson.D{{"city","铁岭"}}
    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 returned result is as follows

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

    Get MongoDB service status

    Above we introduced CRUD for MongoDB. In fact, it also supports many operations on mongoDB, such as aggregation , transactions, etc. Next, let’s introduce the use of golang to obtain MongoDB service status. After execution, it will return a bson.Raw data

    ctx, _ = context.WithTimeout(context.Background(), 30*time.Second)
    serverStatus, err := client.Database("admin").RunCommand(
    ctx,
    bsonx.Doc{{"serverStatus", bsonx.Int32(1)}},
    ).DecodeBytes()
    if err != nil {
    fmt.Println(err)
    }
    fmt.Println(serverStatus)
    fmt.Println(reflect.TypeOf(serverStatus))
    version, err := serverStatus.LookupErr("version")
    fmt.Println(version.StringValue())
    if err != nil {
    fmt.Println(err)
    }

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


Welcome everyone to pay attention to my personal account "Operation and maintenance development story"
Use golang driver to operate MongoDB database

Guess you like

Origin blog.51cto.com/12970189/2547518