2019年3月,发布了适用于MongoDB的正式的可用于生产环境的GO驱动程序,该驱动程序自发布以来一直在持续更新。在本教程中,我们将学习使用Go驱动程序执行简单的MongoDB CRUD操作。

环境准备

在开始本教程之前,需要做两件事。

  • Go应该安装在您的机器上。本教程使用Go 1.15版。
  • 在您的电脑上安装最新版本的MongoDB并启动MongoDB的本地服务器。

安装MongoDB驱动程序

通过运行以下命令来安装MongoDB go驱动程序:

go get go.mongodb.org``/mongo-driver

如果您正在使用Go Modules,则创建一个go.mod文件,然后上述命令将在mod文件中添加所需的依赖项。该文件将所有项目要求锁定为正确的版本。

设置主文件

在您的项目文件夹中创建一个文件main.go,然后在您的IDE中打开它。在编写用于MongoDB操作的代码之前,让我们将所有必需的包导入文件中。

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" 
)

现在,创建以下全局变量,我们将在所有CRUD操作函数中使用这些全局变量。

var client *mongo.Client 
var collection *mongo.Collection 
var ctx = context.TODO()

此外,创建文档类型的结构。

ype Person struct {
 
    Name string 
    Age  int 
    City string 
}

连接到MongoDB

现在基本设置已准备就绪。让我们创建第一个函数以连接到MongoDB。

func connect() *mongo.Client { 
  clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") 
  client, err := mongo.Connect(ctx, clientOptions) 
  if err != nil { 
       log.Fatal(err) 
  }
 
  err = client.Ping(ctx, nil) 
  if err != nil { 
       log.Fatal(err) 
  }
 
  fmt.Println("Connected to MongoDB!") 
  return client 
}

此函数将建立与我们本地运行的MongoDB的连接,并返回客户端对象。一旦connect方法返回了客户端对象,我们就可以使用Ping()方法检查连接是否成功。如果Ping()方法返回任何错误,我们可以引发错误并返回。

插入操作

要只插入一个文档,可以使用insertOne方法,而要一起插入多个文档,可以使用insertMany方法。以下是在“个人”集合中插入一个文档的功能:

func insertOne() { 
  akash := Person{"Akash", 28, "Bengaluru"} 
  res, err := collection. InsertOne (ctx, akash) 
  if err != nil { 
       log.Fatal(err) 
  } 
  fmt.Println("Inserted document: ", res.InsertedID) 
}

这是将多个文档添加到集合的功能:

func insertMany() {
   akash := Person{"Akash", 28, "Bengaluru"} 
  bob := Person {"Bob", 30, "New York"} 
  robin := Person {"Robin", 25, "London"} 
  persons := []interface{}{akash, bob, robin}
  res, err := collection.InsertMany(ctx, persons)
 
  if err != nil { 
       log.Fatal(err) 
  } 
  fmt.Println("Inserted documents: ", res.InsertedIDs) 
}

对于这两个操作,我们都需要使用之前创建的Person结构,并使用我们的数据对其进行初始化。使用InsertMany函数,我们将需要为所有文档传递类型接口。

检索操作

为了从集合中查找数据,我们将需要通过过滤器,因此请确保已导入bson包。我们将使用bson.D类型使用bson对象创建过滤器。

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

同样,我们可以使用Find方法检索所有匹配的文档。

func retrieveAll() { 
  findOptions := options.Find() 
  findOptions.SetLimit(2) 
  var results []*Person 
  cur, err := collection.Find(ctx, bson.D{{}}, findOptions) 
  if err != nil { 
       log.Fatal(err) 
  }
 
  // Loop through the cursor 
  for cur.Next(context.TODO()) { 
       var elem Person 
       err := cur.Decode(&elem) 
       if err != nil { 
            log.Fatal(err) 
       } 
       results = append(results, &elem) 
  }
 
  if err := cur.Err(); err != nil { 
       log.Fatal(err) 
  } 
  cur.Close(context.TODO()) 
}

您可以使用选项包来指定诸如限价或定单之类的选项。

更新操作

与FineOne方法相同,要进行更新,也可以将UpdateOne方法与bson过滤器对象一起使用。此代码将更新所有名称为Akash的文档,并将Age的值增加一。

func update() { 
	filter := bson.D{{"name", "Akash"}} 
    update := bson.D{ 
         {"$inc", bson.D{ 
             {"Age", 1}, 
         }}, 
    } 
    updateResult, err := collection.UpdateOne(context.TODO(), filter, update) 
    if err != nil { 
         log.Fatal(err) 
    } 
    fmt.Printf("Updated documents: %+v\n", updateResult) 
}

删除操作

要从任何集合中删除文档,可以使用DeleteOne或DeleteMany方法。同样,在这里,我们可以传递bson过滤器对象以匹配文档并删除它们。

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

如果将bson.D {{}}对象作为过滤器参数传递,则它将删除所有文档。您可以使用collection.Drop()方法删除整个集合。

所有这些功能准备就绪后,您可以根据需要在驱动程序功能中使用它们。希望这足以使您开始使用Go编写MongoDB函数。有关更多信息,您可以参考Go Mongo驱动程序的官方文档。