我很难阅读文档。基本上,我有一个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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句