Home > front end >  $in operator gives error if pass blank array into it
$in operator gives error if pass blank array into it

Time:12-02

I have worked on the Go and MongoDb project. In which, I have faced a problem. I have passed a dynamic slice of integeres ([]int) into a query using $in operator. Every thing seems good but when this slice is empty then it return an error "$in needs an array". But i used it as a search parameter and want if i pass blank array then it matched with all.

Note: I have userd MongoDB shell version v5.0.3

Here is my code:

var searchedProfiles []int
searchFilter := bson.M{"customer.id": bson.M{"$in": searchedProfiles}}
newQry := []bson.M{
    {"$lookup": bson.M{
        "localField":   "cid",
        "from":         "customers",
        "foreignField": "_id",
        "as":           "customer"}},
    {"$match": searchFilter},
}

If anybody have any idea please let me know. Thanks!

CodePudding user response:

nil values aren't marshaled as empty arrays, so make sure searchedProfiles is not nil but at least an empty slice:

searchedProfiles = []int{}

This will be marshaled into an empty array, so you won't get the error in question.

But this will not give you all documents, this will give you no results (nothing is in the empty list).

If there are no searched profiles, leave this out from the filtering.

  • Related