0

I have a aggregation function in which there are nested lookups with pipeline. In one of the pipeline I have the following -

{
 "$addFields": {
  "ids": {
     "$split": ["$id", ","]
   }
  }
},
{
 "$lookup": {
   "from": 'collection2',
   "let": {"new_id": "$ids"},
    "pipeline": [
     { "$match": {
        "$expr": {
           "$in": ["$ID", "$$new_id"]
         }  
        } 
      }
     ],
    "as": 'groups'
   }
  }

In the above pipeline addFields is splitting the comma separated value in "id" and adding it to an array named "ids".

This "ids" I am using it in lookup below to find the data from other collection using "$in".

But I am getting this error in MongoDB Compass - $in requires an array as a second argument, found: null.

I tried the same by using just this pipeline in a separate aggregation pipeline in Compass where I am getting the results properly but when I include the same in my nested lookup pipeline its not working and giving the above error.

Is it because of nesting or any local variable or any other issue?

Shubhankar
  • 11
  • 2

1 Answers1

0

The error message $in requires an array as a second argument, found: null is indicating that there was a value found, and it was null.

If no value was found at all, the error would have been "$in requires an array as a second argument, found: missing"

The mostly likely problem is that one or more documents in the collection don't have an id field, so the $split returns null.

To work around this, you might use the $ifNull operator to return an empty array when $split returns null, like:

{"$addFields": {
  "ids": {
     "$ifNull":[
          {"$split": ["$id", ","]},
          []
     ]
   }
  }
}
Joe
  • 25,000
  • 3
  • 22
  • 44