gpt4 book ai didi

mongodb - 如何在 Go 中使用 mgo 对文档进行部分和全部更新

转载 作者:IT王子 更新时间:2023-10-29 02:04:11 25 4
gpt4 key购买 nike

来自 Shiju Varghese 的 Web Development with Go,关于 Go 中 MongoDB 驱动 mgo 的更新方法

Updating Documents

The Update method of the Collection type allows you to update existing documents. Here is the method signature of the Update method:

func (c *Collection) Update(selector interface{}, update interface{}) error

The Update method finds a single document from the collection, matches it with the provided selector document, and modifies it based on the provided update document. A partial update can be done by using the keyword "$set" in the update document.

Listing 8-14 updates an existing document.

err := c.Update(bson.M{"_id": id},
bson.M{"$set": bson.M{
"description": "Create open-source projects",
"tasks": []Task{
Task{" Evaluate Negroni Project", time.Date(2015, time.August, 15, 0, 0, 0,
0, time.UTC)},
Task{" Explore mgo Project", time.Date(2015, time.August, 10, 0, 0, 0, 0,
time.UTC)},
Task{" Explore Gorilla Toolkit", time.Date(2015, time.August, 10, 0, 0, 0, 0,
time.UTC)},
},
}})

A partial update is performed for the fields’ descriptions and tasks. The Update method finds the document with the provided _id value and modifies the fields based on the provided document.

该示例是部分更新。它使用两级嵌套 bson.M 来创建更新接口(interface){}。部分更新是否总是使用这样的两级嵌套 bson.M

全量更新是否使用一级bson.M,如

err := c.Update(bson.M{"_id": id},
bson.M{ "description": "Create open-source projects",
"tasks": []Task{
Task{" Evaluate Negroni Project", time.Date(2015, time.August, 15, 0, 0, 0,
0, time.UTC)},
Task{" Explore mgo Project", time.Date(2015, time.August, 10, 0, 0, 0, 0,
time.UTC)},
Task{" Explore Gorilla Toolkit", time.Date(2015, time.August, 10, 0, 0, 0, 0,
time.UTC)},
},
})

谢谢。

最佳答案

  1. 是的,部分更新总是需要$set。这不是关于 Go 这是关于 Mongo $set operator bson.M 只是 map[string]interface{} 的快捷方式,它允许我们在不考虑参数类型的情况下构建类似 JSON 的结构。因此,由于您始终需要 $set,因此更新文档始终至少有两个级别的 bson.M。实际上,还有更多级别,因为您的 Task 对象也可以定义为 bson.M 对象。

  2. 是的,完整的文档更新(我个人认为这个过程看起来更像是替换)只需要 2 个 bson.M 对象——查询和新文档。

    在 Mongo 中完整更新看起来像

    db.collection.update({_id: "id"}, {name: "name", num: 1})

    Go 中同样的命令:

    c.Update(bson.M{"_id": "id"}, bson.M{"name": "name", "num": 1})

关于mongodb - 如何在 Go 中使用 mgo 对文档进行部分和全部更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38747478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com