database - 如果过滤器没有返回任何内容,如何插入文档,否则将在 mongodb 中找到的文档替换为 go?
问题描述
我没有像在这个例子中那样使用 MGO 包,只是来自这里的活动仓库。
我很难阅读文档。基本上,我有一个要替换当前对象的 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
我确信我可以手动运行另一个查询来查看文档是否存在,但这似乎没有必要。谢谢!
编辑:
看起来应该有办法做某事replaceOptions
,请参阅文档。
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))
推荐阅读
- ruby-on-rails - 如何在移动性中使用语言环境或失败访问器验证翻译?
- python - Python中的最佳拟合线不准确
- javascript - jQuery preventDefault() 不能与 .on() 一起使用
- google-apps-script - 扩展 Google 表格脚本
- javascript - 如何更新 WeakMap 中现有键的值?
- sequelize.js - Sequelize - 根据另一个字段的值返回新字段
- python - PermissionError:[Errno 13] 权限被拒绝:'C:\\Users\\***\\Desktop\\***\\BA\\Data.xlsx'
- python - Python:将数据内插到特定的 x 值
- javascript - 视口的内容大小不正确
- reactjs - npm add react-icons 安装不起作用