database - 如果过滤器不返回任何内容,如何插入文档,否则用go替换mongodb中找到的文档?

标签 database mongodb go insert

我没有像this示例中那样使用MGO包,而只是使用了here中的 Activity 存储库。

我很难阅读documentation。基本上,我有一个bson.M对象,我想替换当前对象,如果该对象不存在,则将其插入。

目前,我的代码如下:

updateFilter := bson.D{{"from_symbol", fromSymbol}, {"to_symbol", strings.ToUpper(currency["to_symbol"].(string))}}
// The above seems to be correctly finding the documents I want
// currency is my bson.M object

_, err := collection.ReplaceOne(ctx, updateFilter, currency)
// However this line will not additionally insert if the object is not found, it is replacing fine

我确定我可以手动运行另一个查询以查看文档是否存在,但这似乎是不必要的。
谢谢!

编辑:

似乎应该有一种方法可以处理replaceOptionssee the documentation

upsert := options.ReplaceOptions{Upsert: true}
_, err := collection.ReplaceOne(ctx, updateFilter, currency, upset)

但这给了我错误:
cannot use true (type bool) as type *bool in field value

最佳答案

使用SetUpsert函数:

collection.ReplaceOne(ctx,filter,newDoc,options.Replace().SetUpsert(true))

关于database - 如果过滤器不返回任何内容,如何插入文档,否则用go替换mongodb中找到的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61378655/

相关文章:

java - Neo4j:使用参数时 REST API 速度较慢

mysql - OUTER JOIN MySQL 中的三个不同表时出现的问题

sql - 有没有不使用主键的好情况?

GO解析自定义时间

angularjs - $http.post() 方法实际上是发送一个 GET

mysql - 数据库建模故障排除

javascript - NodeJS 变量作用域

javascript - 如何使用 ajax.get 调用从 node.js 服务器获取响应

mysql - MongoDB 相当于 MYSQL concat()

database - 如何使用这些包 "google.golang.org/appengine/mail"在 Go 中上传附件