为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
aluckdog 2022-07-11 16:23:02
我正在尝试检查订阅部分是否存在,以及它是否包含至少一个名为 premium 的变量,其值为 true。如果是,它应该返回,如果不是,它不应该返回。目前它正在返回集合中的对象,即使该值设置为 false。// query to find all the users accounts that have purchased premium subscriptionshasPurchasedSubscriptions := 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}}},        }},    })}})
查看完整描述

1 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

只需使用:


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

})


查看完整回答
反对 回复 2022-07-11
  • 1 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号