以下是使用 Go MongoDB 驱动程序的 FindOneAndUpdate 的简单示例:
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"
)
type Person struct {
Name string `bson:"name,omitempty"`
Age int `bson:"age,omitempty"`
Country string `bson:"country,omitempty"`
}
func main() {
// 连接到 MongoDB
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(context.Background())
// 获取数据库和集合
db := client.Database("mydb")
peopleColl := db.Collection("people")
// 创建筛选器
filter := bson.M{"name": "Alice"}
// 创建更新器
update := bson.M{
"$set": bson.M{
"age": 30,
},
}
// 运行 FindOneAndUpdate 操作
var result Person
opts := options.FindOneAndUpdate().SetReturnDocument(options.After)
err = peopleColl.FindOneAndUpdate(context.Background(), filter, update, opts).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("更新成功:%s\n", result.Name)
}
此示例中的 FindOneAndUpdate
操作执行以下步骤:
- 在
people
集合中,查找符合筛选器条件"name": "Alice"
的第一条文档。 - 对于找到的文档,使用更新器更新其
"age"
字段。 - 返回更新后的文档(使用
SetReturnDocument(options.After)
)。 - 将更新后的文档解码到
Person
结构体中(使用Decode(&result)
)。 - 在控制台输出更新后的Person对象。
希望这个示例可以帮助你使用 Go MongoDB 驱动程序中的 FindOneAndUpdate 操作。