conditional stages or conditional pipeline in aggregation

765 views
Skip to first unread message

timath...@gmail.com

unread,
Mar 1, 2018, 8:14:36 PM3/1/18
to mongodb-user

there's the prices collection.

[

{ "_id":"...683d", "brandId":"...f31c", "model":"N5", "pwId":"...1b67", "number":50 }

,

{ "_id":"...683e", "brandId":"...f31c", "model":"base", "pwId":"...1b67", "number":40 }

, ...]

there's the items collection.

[

{ "_id":"...31aa", "pwId":"...1b67", "brandId":"...f31c", "model":"abc", "series": "N5", "bms": "yyn" }

, ...]

I'd like to get the price for the items and the steps are:

1. check `item.bms`, if `bms === 'yyn'`, use sub-pipeline-a, otherwise, use sub-pipeline-b;
2. let's look at sub-pipeline-a, while sub-pipeline-b could be similar.
2.1 lookup price with three conditons, `pwId + brandId + model`, if found, go no further;
2.2 if not found, try `pwId + brandId + series`(`item.series` as `price.model)`, if found, go no further;
2.3 if still not found, try `pwId + brandId + 'base'`(use string `'base'` as `price.model`);
3. combine the result of both sub-pipeline-a and sub-pipeline-b.

For step 1, I'm using a `$facet` stage. For step 2.1 through 2.3, I'm running 3 `$lookup`s one after another, which is obviously a waste of resources.

How to decide whether to run 2.2 based on result of 2.1?
Thanks.

Kevin Adistambha

unread,
Mar 8, 2018, 11:20:49 PM3/8/18
to mongodb-user

Hi

The aggregation pipeline works by passing documents from one stage to the next. While it can process basic conditionals such as $cond and multiple pipes using $facet, the aggregation pipeline itself is not Turing complete (e.g. it doesn’t have functions, goto statements, etc.).

If you require complex logic, it’s better to implement it in the application side instead.

Best regards
Kevin

Reply all
Reply to author
Forward
0 new messages