Is it possible to have conditional stages?


I tried to do an conditional $lookup, and i added a filter on top of its pipeline.
That filter doesn’t need the other collection, but its not optimized.
I think there is no way to have conditional stage, so i tried this hoping that it would be optimized.

Inside the lookup pipeline

let : ["a" "$a"]
pipeline : [(= "$$a" -1)]       

"$$a" is never -1 so never lookup is needed, its always [] , without any need to even check the other collection, but its not optimized, costs similar to a lookup that would read the document from the other collection.

Is there a way to make conditional stages, in general?
(i only know a way to undo $set using $$REMOVE )

Thank you

Hi @Takis,

I don’t think conditional stages are a thing indeed. At least I never heard of it.

The only thing that is kinda related to what you are explaining is $cond.

Could you try to explain your problem instead and share some example docs + the expected output docs so we can try to find another way to achieve your goal?

Another way to add/remove dynamically stages in the pipeline would be to build the pipeline dynamically in the back-end and send or not each stage based on a given condition.



Thank you, i dont think there are conditional stages also.

I just hoped mongodb to optimize it.

Look up can be like 3 cases (here top filters on the pipeline)

  1. filter false without need data from either collection
    example (= 1 2)
  2. filter false using data from left collection only
    example (= "$$a" 1) ("$$a" variable from left collection that is never 1)
  3. filter false using data from left+right collection
    example (= "$$a" "$b") "$$a" from left collection "$b" field from right collection

Only in the 3rd case it actually needs to read the right(other) collection.
But it seems that does the 3rd option it in both case 2 and 3 (no optimized), i think in case 1 its optimized but not sure,so optional lookup costs similar to normal lookup i think.