猿问

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

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


如果是,它应该返回,如果不是,它不应该返回。目前它正在返回集合中的对象,即使该值设置为 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}}},

        }},

    })

}

})


aluckdog
浏览 111回答 1
1回答

慕村225694

只需使用: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},})
随时随地看视频慕课网APP

相关分类

Go
我要回答