我正在嘗試檢查訂閱部分是否存在,以及它是否包含至少一個名為 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},
})
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報
0/150
提交
取消