Docs 菜单
Docs 主页
/ / /
Go 驱动程序
/ /

更新文档

您可以使用 UpdateOne() 方法更新集合中的文档。

提示

参阅“使用示例”,了解如何运行此示例。

以下示例对 restaurants 集合执行以下操作:

  • 将文档与特定 _id 相匹配 _id

  • 在匹配的文档中创建一个名为 avg_rating 且值为 4.4 的新字段(Field)

coll := client.Database("sample_restaurants").Collection("restaurants")
id, _ := primitive.ObjectIDFromHex("5eb3d668b31de5d588f42a7a")
filter := bson.D{{"_id", id}}
// Creates instructions to add the "avg_rating" field to documents
update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}}
// Updates the first document that has the specified "_id" value
result, err := coll.UpdateOne(context.TODO(), filter, update)
if err != nil {
panic(err)
}

查看 完全可运行的示例。

运行完整示例后,您可在 restaurants 集合中找到以下更新后的文档:

// result truncated
{
"_id" : ObjectId("5eb3d668b31de5d588f42a7a"),
...
"name" : "Green House Cafe",
"restaurant_id" : "40372112",
"avg_rating" : 4.4
}

有关如何查找文档的示例,请参阅查找文档

要了解有关替换文档、指定查询筛选器和处理潜在错误的更多信息,请参阅修改文档。

要了解有关更新操作符的更多信息,请参阅MongoDB 更新操作符参考文档。

UpdateOne()

← 插入多个文档