为了账号安全,请及时绑定邮箱和手机立即绑定

如果过滤器没有返回任何内容,如何插入文档,否则将在 mongodb 中找到的文档替换为 go?

如果过滤器没有返回任何内容,如何插入文档,否则将在 mongodb 中找到的文档替换为 go?

Go
杨魅力 2022-06-01 11:28:12
我没有像在这个例子中那样使用 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
查看完整描述

1 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

使用SetUpsert功能:

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


查看完整回答
反对 回复 2022-06-01
  • 1 回答
  • 0 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号