替换 MongoDB 中的文档:使用 Go 驱动程序的方法
来源:stackoverflow
时间:2024-02-20 21:30:26 463浏览 收藏
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《替换 MongoDB 中的文档:使用 Go 驱动程序的方法》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
我正在尝试使用 mongodb/mongo-go-driver
更新 mongodb 中的文档。从其文档来看,一个文档可以替换为:
var coll *mongo.collection var id primitive.objectid // find the document for which the _id field matches id and add a field called "location" // specify the upsert option to insert a new document if a document matching the filter isn't found opts := options.replace().setupsert(true) filter := bson.d{{"_id", id}} replacement := bson.d{{"location", "nyc"}} result, err := coll.replaceone(context.todo(), filter, replacement, opts) if err != nil { log.fatal(err) } if result.matchedcount != 0 { fmt.println("matched and replaced an existing document") return } if result.upsertedcount != 0 { fmt.printf("inserted a new document with id %v\n", result.upsertedid) }
但是如果我的字段超过 20 个怎么办?我想知道是否可以更新而无需再次重写所有字段,我尝试了这样的操作:
// Replacement struct type Input struct { Name *string `json:"name,omitempty" bson:"name,omitempty" validate:"required"` Description *string `json:"description,omitempty" bson:"description,omitempty"` Location *string `json:"location,omitempty" bson:"location,omitempty"` } ... oid, _ := primitive.ObjectIDFromHex(id) // because 'id' from request is string filter := bson.M{"_id", oid} // throws `[compiler] [E] missing key in map literal` // ^^^ replacement := bson.D{{"$set", input}} // throws `composite literal uses unkeyed fields` // ^^^^^ result, err := coll.ReplaceOne(context.TODO(), filter, replacement, opts) ...
但它会在过滤和替换时引发错误。如何正确替换整个文档?
解决方案
bson.M
是一个地图,所以如果使用的话,就得写:bson.m{"_id": oid}
。参见missing type in composite literal go AND missing key in map literal go。
而bson.D
是一个结构体切片,所以如果使用它,应该写成bson.d{{key:"$set", value: input}}
。省略字段名称不是编译器错误,这只是一个 go vet 警告。
现在开始更换。替换必须是文档本身,不能使用$set
(这不是更新而是替换)。有关参考,请参阅 mongodb 的 collection.replaceOne()
和驱动程序的文档:Collection.ReplaceOne()
:
替换参数必须是将用于替换所选文档的文档。它不能为零,也不能包含任何更新运算符 (https://docs.mongodb.com/manual/reference/operator/update/)。
所以这样做:
filter := bson.m{"_id": oid} result, err := coll.replaceone(context.todo(), filter, input, opts)
这是完整的代码。这将有助于读者理解代码流程。
func UpdateFunction(echoCtx echo.Context) (error) { //Web Section documentID := echoCtx.Param("id") //Provided in URL var newObject myStruct err := echoCtx.Bind(&newObject) // Json with updated values sent by web client mapped to struct ctx := echoCtx.Request().Context() //Database Section database := db.Conn.Database("myDatabase") collection := database.Collection("myCollection") existingHexID, err := primitive.ObjectIDFromHex(documentID) if err != nil { fmt.Println("ObjectIDFromHex ERROR", err) } else { fmt.Println("ObjectIDFromHex:", existingHexID) } // Replacing OLD document with new using _id filter := bson.M{"_id": newDocumentID} result, err := collection.ReplaceOne(ctx, filter, newObject) if err != nil { log.Fatal(err) } fmt.Printf( "insert: %d, updated: %d, deleted: %d /n", result.MatchedCount, result.ModifiedCount, result.UpsertedCount, ) return echoCtx.JSON(http.StatusOK, result.ModifiedCount) }
到这里,我们也就讲完了《替换 MongoDB 中的文档:使用 Go 驱动程序的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习