首先,我们需要在go中安装MongoDB的驱动包,使用命令go get go.mongodb.org/mongo-driver/mongo进行安装.
接着,在代码中导入mongo driver的包,并建立与MongoDB的连接,示例代码如下:
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func establishConnection() (*mongo.Client, error) {
ctx := context.TODO()
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
return nil, err
}
return client, nil
}
此时此刻呢,我们需要在MongoDB中创建一个数据库以及集合,示例代码如下:
func createCollection(client *mongo.Client) error {
ctx := context.TODO()
database := client.Database("testdb")
collOption := options.Collection().SetMaxAge(300)
collection := database.Collection("testcoll", collOption)
_, err := collection.Indexes().CreateMany(ctx, []mongo.IndexModel{
return err
}
return nil
}
此时此刻呢,我们可以执行一些CURD操作,示例如下:
func insertDocument(client *mongo.Client) error {
ctx := context.TODO()
database := client.Database("testdb")
collection := database.Collection("testcoll")
doc := bson.M{
return results, err
}
return results, nil
}
以上示例代码演示了如何建立与MongoDB的连接、创建数据库集合以及如何进行CURD操作.