'appending if-else condition in mongodb golang

I am new to using Mongo DB and trying to write this mongo query in golang. Basically, I am trying to set the field ready to true or false based on certain situation given below.

db.getCollection('product_repo').update({catalog_global_id: "123-def-xyz"}, [{
    $set: {
        "ready": {
            $cond: [
              {$and: [
                  {$ne: ["enable_catalog", null]}, 
                  {$ne: ["enable_pricing", null]}
              ]}, true, false
            ]
        }
    }
}])

Now, my go query in golang, looks like this.

query := []bson.M{
        {
            "$cond": bson.M{
                "$if": bson.M{
                    "$ne": bson.M{
                        "enable_catalog": nil,
                    },
                },
                "then": true,
                "else": false,
            },
        },
    }

The issue is, my field "$enable_pricing" will only be added if the flag is enabled, so this is where I am stuck. I tried doing this.

    if isPricingEnabled() {
        query = append(clauses, bson.M{
            "$ne": bson.M{
                "pricing_attributes": nil,
            },
        })
    }

Now, I know I am doing something wrong here because my golang query is failing, but not sure what am I missing and what can I do to fix it. What could I be possibly missing here?.



Solution 1:[1]

before forming the query you can create the and block like this. and then use that in the final query

andQuery := []bson.M{{
        "$ne": bson.A{"anable_catalog", nil},
    }}

if isPricingEnabled(){
        andQuery = append(andQuery, bson.M{"$ne": bson.A{ "enable_pricing", nil}})
}
query := bson.M{
    "$cond": bson.M{
        "if": bson.M{
            "$and": andQuery,
        },
        "then": true,
        "else": false,
    },
}
var updateData  = bson.M{
    "$set": bson.M{
        "ready" : query,
    },
}

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