如果 slice 存在并且它包含至少一个设置为 true 的特定变量

If slice exists and if it contains at least one specific variable set to true

我正在尝试检查订阅片段是否存在,以及它是否包含至少一个名为 premium 且值为 true 的变量。

如果是,则应该 return,如果不是,则不应 return。 当前它正在 return 收集集合中的对象,即使该值设置为 false。

// query to find all the users accounts that have purchased premium subscriptions
hasPurchasedSubscriptions := c.QueryParam("hasPurchasedSubscriptions")
if hasPurchasedSubscriptions != "" {

    pipeline = append(pipeline, bson.M{
        "$match": bson.M{"$and": []interface{}{
            bson.M{"subscriptions": bson.M{"$exists": true}},
            bson.M{"subscriptions": bson.M{"$elemMatch": bson.M{"premium": true}}},
        }},
    })
}
})

只需使用:

pipeline = append(pipeline, bson.M{
    "$match": bson.M{
        "subscriptions": bson.M{"$elemMatch": bson.M{"premium": true}},
    },
})

不需要检查它是否存在,它必须存在,否则它不能有带有premium=true的元素。

如果你的元素只有这一个条件,你也可以简化为:

pipeline = append(pipeline, bson.M{
    "$match": bson.M{"subscriptions.premium": true},
})