how to use MongoDB $cond in golang

huangapple go评论87阅读模式
英文:

how to use MongoDB $cond in golang

问题

我正在尝试在MongoDB中有条件地更新一个字段,期望的结果是如果字段不存在,则更新为新数据,但我得到的结果是data = {$cond:["exist", "data", newdata]}

以下是我的代码:

update := bson.M{"$set": bson.M{"data": bson.M{"$cond": []interface{}{"exist", "data", newdata}}}}
collection.UpdateByID(id, update)

有人可以帮我看看吗?

英文:

I'm trying to conditionally update a field in MongoDB, the expected result is newdata if not exist, but the result I got is data = {$cond:[exist", "data", newdata]}

Here is my code:

update := bson.M{"$set": bson.M{"data": bson.M{"$cond": []interface{}{"exist", "data", newdata}}}}
collection.UpdateByID(id, update)

Any one can help me take a look?

答案1

得分: 0

如果你不想在存在数据时更改数据,你可以使用$ifNull聚合函数:

update := bson.A{bson.M{$set:bson.M{"data":bson.M{"$ifNull":bson.A{"$data",newdata}}}}}

否则,如果你想在任何情况下设置数据,目前似乎没有一种方法可以在一次更新中完成。所以你必须使用两个独立的更新和两个反向过滤器来完成,如下所示:

// 第一个过滤器
bson.M{"data":{"$exists":true}}
// 第二个过滤器
bson.M{"data":{"$exists":false}}

请注意,使用bson.A来实现数组(用方括号[]表示)

英文:

If you don't want to change data when exists then you can use $ifNull aggrigation:

update := bson.A{bson.M{$set:bson.M{"data":bson.M{"$ifNull":bson.A{"$data",newdata}}}}}

Otherwise if you want to set data in any case; there seems to be no way to do this in one update right now.
So you must do it in two separate updates with two inverted filters like these:

//first filter
 bson.M{"data":{"$exists":true}}
//second filter
 bson.M{"data":{"$exists":false}}

<i>Note that use bson.A to implement arrays (Known by brackets [])</i>

huangapple
  • 本文由 发表于 2022年3月25日 03:40:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/71608498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定