Laravel 5 Eloquent sum of multiplied columns for mongo DB

后端 未结 1 1774
死守一世寂寞
死守一世寂寞 2021-01-15 22:31
This is my invoices mongo table 

{
    \'_id\': ObjectId(\"565d78336fe444611a8b4593\"),
    \'TransactionID\': \'X020\',
    \'Type\': \'SALESINVOICE\',
    \'Invoi         


        
相关标签:
1条回答
  • 2021-01-15 23:10

    I believe aggregation operators like sum expect exact column name as a parameter. You can try to project the multiplication first, then sum the result:

    DB::connection($this->MongoSchemaName)
        ->collection($this->InvoicesTable)
        ->where('ContactID', (int)$customer->ContactID)
        ->project([
            'ContactID' => 1, 
            'TotalInBaseCurrency' => ['$multiply' => ['$Total', '$CurrencyRate']]
        ])
        ->sum('TotalInBaseCurrency')
    

    or use aggregation directly:

    DB::connection($this->MongoSchemaName)
        ->collection($this->InvoicesTable)
        ->raw(function($collection) use ($customer){
            return $collection->aggregate([
                ['$match' => [
                        'ContactID' => (int)$customer->ContactID,
                        'Type' => 'PAYMENT'
                    ]
                ],
                ['$group' => [
                    '_id' => '$ContactID',
                    'TotalInBaseCurrency' => [
                            '$sum' => ['$multiply' => ['$Total', '$CurrencyRate']]
                        ]
                    ]
                ]
            ]);
        })
    
    0 讨论(0)
提交回复
热议问题