mongodbgoconditional-operator

Why is it saving the whole mongodb clause not the timestamp?


When I am running it it's saving this whole clause

“$cond”: bson.M{
        “if”:   bson.M{“$eq”: bson.A{“$date”, nil}},
        “then”: time.Now(),
        “else”: “$date”,
    },

in the document. What did I do wrong here can anyone please explain? (I am using findOneAndupdate())

update[“$set”].(bson.M)[“date”] = bson.M{
            “$cond”: bson.M{
                “if”:   bson.M{“$eq”: bson.A{“$date”, nil}},
                “then”: time.Now(),
                “else”: “$date”,
            },
        }

Solution

  • Here is the updated code that worked for me -

    update := bson.A{
                bson.M{
                    "$set": bson.M{
                        "field1": field1_Value,
                        "field2": field2_Value,
                    },
                },
            }
           
        
    update = append(update, bson.M{
                    "$set": bson.M{
                        "field3": field3_value,
                        "field4":  bson.M{"$ifNull": []interface{}{"$field4", field4_value}},
                    },
                })
    

    I found this doc helpful thank you aneroid for commenting-

    https://www.mongodb.com/community/forums/t/mongo-go-driver-update-with-set-cond-aggregation-operator-works-only-when-wrapped-as-array/198416