2015-12-18 57 views
1
This is my invoices mongo table 

{ 
    '_id': ObjectId("565d78336fe444611a8b4593"), 
    'TransactionID': 'X020', 
    'Type': 'SALESINVOICE', 
    'InvoiceNumber': 'ABC020', 
    'Date': '2015-11-01 00:00:00', 
    'DueDate': '2015-12-01 00:00:00', 
    'CurrencyCode': 'GBP', 
    'CurrencyRate': NumberLong(1.2), 
    'Total': NumberLong(200), 
    'PlannedPaymentDate': '', 
    'HasAttachments': 0, 
    'UpdatedDate': '2015-12-01 10:36:35', 
    'AmountDue': NumberLong(200), 
    'AmountPaid': 0, 
    'Status': 'OPEN', 
    'AmountCredited': 0, 
    'AmountDebited': 0, 
    'Source': 1, 
    'InvoiceID': 'csv_1_X020', 
    'ExpectedPaymentDate': '2015-12-01 00:00:00', 
    'ContactID': 1, 
    'ValidateStatus': 'IMPORT', 
    'StatusChangeDate': '' 
} 

我希望兩個領域的乘法什麼(共* CurrencyRate) 我嘗試這個查詢::倍增列Laravel 5雄辯的總和蒙戈DB

DB::connection($this->MongoSchemaName)->collection($this->InvoicesTable)->where('Type', 'PAYMENT')->where('ContactID', (int)$customer->ContactID)->select(DB::raw('sum(Total*CurrencyRate)'))->first(); 

,並試圖更多::

DB::connection($this->MongoSchemaName)->collection($this->InvoicesTable)->where('Type', 'PAYMENT')->where('ContactID', (int)$customer->ContactID)->sum(DB::raw('Total * CurrencyRate')); 

,但沒有得到確切出來把所有的時間我得到0

回答

6

我相信聚合算升ike sum期望確切的列名作爲參數。您可以嘗試project相乘,再總結的結果:

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

或使用聚合直接:

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

我試過,但它給我的錯誤... – rahul

+0

對不起,沒有laravel方便,並沒有測試第一個查詢。第二個應該工作,除非有錯字。你有哪些錯誤?你可以將它們添加到我的答案中。 –

+0

當然有一個錯字。 '$ match'中的括號過多。請嘗試更新的。 –