Running aggregation operator on some of the documents but output entire collection

hello there, lets say i have a collection consisting of products for an ecommerce store. what i want to do is change title for products that are cheaper than 50. that is simple with aggregations with something like this :

[{$match: {
  price: {$lt: 50}
}}, {$set: {
  title: {$concat: ["Cheapest ", '$brand', " you can find ! " ]}
}}]

but, with this approach, the output will only contain products that are cheaper than 50$. and if i want to run some other aggregation on the same collection i have to run another aggregation from start.
what i want to do is pass an argument to $set function and tell it to only work on documents that are cheaper than 50$.
is there a way i can achieve this with aggregations ?

Hi @Ali_ihsan_Erdem1 ,

You can do so with $cond and not $match:

[{$set: {
 title: {
  $cond: {
   'if': {
    $lt: [
     '$price',
     50
    ]
   },
   then: {
    $concat: [
     'Cheapest ',
     '$brand',
     ' you can find!'
    ]
   },
   'else': null
  }
 }
}}]

Thanks,
Pavel

1 Like

@Pavel_Duchovny sir you cant possibly imagine how much this helped me !
i just cant believe i missed this in documentation :confused: this will make my job a lot easier.

@Pavel_Duchovny i have another small question. i tried to use mql syntax with $cond and it didnt work.

[{
    $set: {
        testField: {
            $cond: {
                if: {
                    '$brand': "someBrand"
                },
                then: 20,
                else: 10
            }
        }
    }
}]

but it works with $eq and $ne. how can i determine what will and will not work with $cond ?

Hi @Ali_ihsan_Erdem1 ,

If you look at the documentation the if condition must receive a Boolean expression. Only operators or the Boolean themselves return this. A document expression does not.

Thanks
Pavel

thanks again. so i can use operators safely. but have to convert document expressions to operators. got it !

You need to use the agg $eq expression inside if

{$eq:["$brand", "someBrand"]}