0

I am trying to check if the slice of subscriptions exists, and also if it contains at least one variable called premium with the value of true.

If so it should return, if not it should not return. Currently it is returning the object in the collection even if the value is set to 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}}},
        }},
    })
}
})
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
John
  • 47
  • 1
  • 8

1 Answers1

2

Simply use:

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

No need to check if it exists, it must, else it cannot have an element with premium=true.

And if you have only this one condtion to the element, you may also simplify it to:

pipeline = append(pipeline, bson.M{
    "$match": bson.M{"subscriptions.premium": true},
})
icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you! how would I find if they do not have any premium set to true for the false case? – John Nov 05 '20 at 16:34
  • @John Negate the condition: `{"subscriptions.premium":{$ne:true}}`. This will also return documents where there is no subscriptions field – icza Nov 05 '20 at 16:39