使用Go 连接和操作 Mongo的步骤

23 min read

以下是使用Go连接和操作Mongo的步骤:

  1. 安装 MongoDB Go 驱动程序

Golang与MongoDB之间有许多选择的Go驱动程序。但是,最流行的是MongoDB官方的go-mongo驱动程序。可以使用以下命令在终端中安装它:

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

  1. 创建数据库连接

在Go中连接到MongoDB,需要定义一个MongoDB文档。使用此文档,可以打开MongoDB连接并指向特定的数据库。如下所示创建一个连接:

import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

// Connect to MongoDB
client, err := mongo.Connect(context.Background(), clientOptions)

if err != nil {
log.Fatal(err)
}

// Check the connection
err = client.Ping(context.Background(), nil)

if err != nil {
log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")
}

  1. 创建和查询集合

集合与表格相似,它是MongoDB中存储数据的地方。可以使用以下函数在指定的数据库中创建一个集合:

func createCollection(client *mongo.Client, collectionName string) error {
// Get a handle for your collection
collection := client.Database("myDatabase").Collection(collectionName)

// Check if collection already exists
names, err := client.Database("myDatabase").ListCollectionNames(context.Background(), bson.M{})
if err != nil {
log.Fatal(err)
}
for _, name := range names {
if name == collectionName {
return nil // Collection already exists
}
}

// Create a new collection
createOpts := options.CreateCollection().SetCapped(true).SetMaxBytes(1000000)
if err := client.Database("myDatabase").CreateCollection(context.Background(), collectionName, createOpts); err != nil {
log.Fatal(err)
}
return nil
}

然后,您可以使用find和findOne函数从集合中获取数据。下面这个例子即是从集合中查询所有的记录:

func findDocuments(client *mongo.Client, collectionName string) ([]bson.M, error) {
// Get a handle for your collection
collection := client.Database("myDatabase").Collection(collectionName)

// Find multiple documents
cursor, err := collection.Find(context.Background(), bson.M{})
if err != nil {
return nil, err
}

var results []bson.M
if err = cursor.All(context.Background(), &results); err != nil {
return nil, err
}

return results, nil
}

  1. 插入数据

可以使用InsertOne或InsertMany函数将数据插入集合中。下面这个例子即是插入一条数据到一个集合中:

func insertDocument(client *mongo.Client, collectionName string) error {
// Get a handle for your collection
collection := client.Database("myDatabase").Collection(collectionName)

// Insert a single document
result, err := collection.InsertOne(context.Background(), bson.M{"name": "pi", "value": 3.14159})
if err != nil {
return err
}
fmt.Println("Inserted document with ID:", result.InsertedID)

return nil
}

  1. 更新数据

使用UpdateOne或UpdateMany函数可以更新一个或多个文档。下面是一个例子,用于将一个集合中的一行数据更新为新值:

func updateDocument(client *mongo.Client, collectionName string) error {
// Get a handle for your collection
collection := client.Database("myDatabase").Collection(collectionName)

// Find a document
filter := bson.M{"name": "pi"}
update := bson.M{"$set": bson.M{"value": 3.14159265359}}
result, err := collection.UpdateOne(context.Background(), filter, update)
if err != nil {
return err
}
fmt.Printf("Matched %v documents and updated %v documents\n", result.MatchedCount, result.ModifiedCount)
return nil
}

  1. 删除数据

可以使用DeleteOne或DeleteMany函数从集合中删除文档。以下是一个例子,用于从集合中删除名为“pi”的文档:

func deleteDocument(client *mongo.Client, collectionName string) error {
// Get a handle for your collection
collection := client.Database("myDatabase").Collection(collectionName)

// Delete a document
filter := bson.M{"name": "pi"}
result, err := collection.DeleteOne(context.Background(), filter)
if err != nil {
return err
}
fmt.Printf("Deleted %v documents\n", result.DeletedCount)
return nil
}

以上是使用Go连接和操作Mongo的步骤。通过上面的例子,你可以开始连接并操作你的MongoDB数据库了。@endsection