Search code examples
mongodbgomongo-go

mongo go if [] is empty deem it as false


Currently if a user has a subscriptions object but it is empty i.e [] then it will not be deemed as subscriptions = false.

// hasActiveSubscriptions
hasSubscriptions := c.QueryParam("hasSubscriptions")
if hasSubscriptions != "" {

    hasSubscriptions = strings.ToUpper(hasSubscriptions)
    if hasSubscriptions != "TRUE" && hasSubscriptions != "FALSE" {
        fmt.Println("hasSubscriptions query param is an invalid value")
    }
    res, err := strconv.ParseBool(hasSubscriptions)
    if err != nil {
        fmt.Println(err)
    }
            if res {
        pipeline = append(pipeline, bson.M{
            "$match": bson.M{
                "subscriptions": bson.M{"$ne": nil},
            },
        })
    } else {
        pipeline = append(pipeline, bson.M{
            "$match": bson.M{"subscriptions": nil},
        })
    }

}

This is where the call happens. Currently it returns no objects if I append either of the pipeline query options to the pipeline. I have other simple $match pipeline queries working.

cur, err := collection.Aggregate(ctx, pipeline)
if err != nil {
    return c.String(http.StatusNotFound, "No users found")
}

Solution

  • If the subscriptions field is optional in database, then if you want to filter documents with subscriptions, you have to filter by subscriptions being existent and its size greater than 0 (greater than zero condition is enough, as this can only be if the field exists). Similarly, if you want documents without subscriptions, you have to filter by it being non-existent or its size equal to 0.

    A simpler approach is test for the existance of the first array element. The first array element can only exist if subscriptions exists and its size is greater than 0, and if the first element doesn't exist then subscriptions either does not exist or it's empty.

    So simply use this:

    pipeline = append(pipeline, bson.M{
        "$match": bson.M{
            "subscriptions.0": bson.M{"$exists": res},
        },
    })