我有一个mongo集合,我需要在其中按Payment_id对数据进行分组,此外我还需要获得total_payable
的金额。 total_payable amount
由total_payable+extra_book_price
组成。正常加法正在工作,但是我想针对一个在明细数组内的extra_book_price
为空的情况。
到目前为止,我已经尝试过$exists
和ifNull
,但是它们不起作用。
感谢您的帮助。
如果extra_book_price
不存在,我只需要返回total_payable
。
[
'$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'] ]
]
]
]
]
],
DUMMY DATA
{
"_id":23761,
"gross_total":2499,
"total_payable":2499,
"bookfair_id":110,
"payment_id":2,
"order_detail":[
{
"product_id":"5c63d418ae1db123d8048276",
"amount":2499,
"quantity":1,
"status":1
}
],
"extra_books_detail":{
"employee_id":0,
"total_payable":"100",
"payment_id":1,
"detail":[
{
"amount":"100",
"quantity":1
}
]
},
"status":1
}
AND IF EXTRA BOOK DETAIL
为空
{
"_id":1,
"gross_total":350,
"total_payable":350,
"bookfair_id":300,
"payment_id":1,
"order_detail":[
{
"product_id":"5c4f2a5725956b7e8e7ddba8",
"condition_id":"5c5562df25956b10c02d06d3",
"amount":350,
"quantity":1,
"status":1
}
],
"extra_books_detail":[
],
"status":1,
"date_added":"2018-01-06T06:14:04.000Z"
}