mercredi 27 février 2019

If condition if the field $exists inside $group in mongo

I have a mongo collection in which i need to group the data by payment_id,further i need to get the total_payable amount. The total_payable amount is made of total_payable+extra_book_price. Normal Addition is working but i want to target a scenario in which the extra_book_price that is inside a detail array is empty. So far i have tried $exists and ifNull but they don't work .

Any help is appreciated.

Also if extra_book_price does not exist i need to return the total_payable only.

[
  '$match'=>[
                          'bookfair_id'=>110
                        ]
],
[
  '$group'=> [
                       '_id'=>'$payment_id',
                           'card_pay'=> ['$sum'=> '$total_payable' ],
                           'count'=>[
                                         '$sum'=>[
                                                        '$cond'=> [ 
                                                            'if'=> ['$ifNull'=>['$extra_books_detail',true]], 
                                                            'then'=>['$total_payable'],
                                                            'else'=>['$add'=> ['$total_payable','$extra_books_detail.total_payable'] ]
                                               ]
                                             ]
                                ] 
                                    ]
                                ],



Aucun commentaire:

Enregistrer un commentaire