An aggregation pipeline is simply an array of JSON documents. Nothing stops you from building it dynamically with ifs and whiles. What is interesting in your example is that it looks like you already do some thing close to that with you variable inputs.
You could take M220P from MongoDB University or at least download the course material. It’s full of dynamic queries.