MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Laravel 5 Eloquente Summe multiplizierter Spalten für Mongo DB

Ich glaube Aggregationsoperatoren wie sum erwarten Sie den genauen Spaltennamen als Parameter. Sie können versuchen, project zuerst die Multiplikation, dann das Ergebnis summieren:

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

oder verwenden Sie die Aggregation direkt:

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']]
                    ]
                ]
            ]
        ]);
    })