'how to use MongoDB $cond in golang

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?



Solution 1:[1]

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}}

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1