func main() {
 // 创建一个上下文对象
 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 defer cancel()
// 创建一个MongoDB的客户端
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    fmt.Println("Failed to connect to MongoDB:", err)
    return
}

// 检查连接是否成功
err = client.Ping(ctx, nil)
if err != nil {
    fmt.Println("Failed to ping MongoDB:", err)
    return
}

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

在上面的代码中,我们使用`mongo.Connect`函数来连接到MongoDB数据库,并使用`client.Ping`函数检查连接是否成功。在实际使用中,你可能需要根据自己的需求进行配置和调优。

#### 插入数据

一旦连接到MongoDB,我们就可以开始插入数据。下面是一个简单的示例,演示如何向MongoDB插入一条数据:

package main
import (
 “context”
 “fmt”
 “go.mongodb.org/mongo-driver/bson”
 “go.mongodb.org/mongo-driver/mongo”
 “go.mongodb.org/mongo-driver/mongo/options”
 “time”
 )type Person struct {
 Name string
 Age int
 }func main() {
 // 创建一个上下文对象
 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 defer cancel()
// 创建一个MongoDB的客户端
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    fmt.Println("Failed to connect to MongoDB:", err)
    return
}

// 检查连接是否成功
err = client.Ping(ctx, nil)
if err != nil {
    fmt.Println("Failed to ping MongoDB:", err)
    return
}

// 选择数据库和集合
collection := client.Database("mydb").Collection("persons")

// 创建一个Person对象
person := Person{
    Name: "Alice",
    Age:  25,
}

// 插入数据
\_, err = collection.InsertOne(ctx, person)
if err != nil {
    fmt.Println("Failed to insert data:", err)
    return
}

fmt.Println("Data inserted successfully!")
}

在上面的代码中,我们首先选择了一个名为"mydb"的数据库和一个名为"persons"的集合。然后,我们创建了一个Person对象,并使用`collection.InsertOne`函数将其插入到MongoDB中。如果一切顺利,你将看到"Data inserted successfully!"的输出。

#### 查询数据

除了插入数据,我们还可以使用Golang从MongoDB中查询数据。下面是一个简单的示例,演示了如何查询MongoDB中的数据:

package main
import (
 “context”
 “fmt”
 “go.mongodb.org/mongo-driver/bson”
 “go.mongodb.org/mongo-driver/mongo”
 “go.mongodb.org/mongo-driver/mongo/options”
 “time”
 )type Person struct {
 Name string
 Age int
 }func main() {
 // 创建一个上下文对象
 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 defer cancel()
// 创建一个MongoDB的客户端
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    fmt.Println("Failed to connect to MongoDB:", err)
    return
}

// 检查连接是否成功
err = client.Ping(ctx, nil)
if err != nil {
    fmt.Println("Failed to ping MongoDB:", err)
    return
}

// 选择数据库和集合