2016-08-23 96 views
2

我已经有一个解决方案,但我在看这确实对MongoServer所有作业(因为我觉得这是更快,更少的内存消耗)如何获得MongoDB中两个字段的差异总和?

我有一类方法的解决方案,如:

function getTotalOutstandingAmount(){ 
    $outstandingAmount = 0; 
    $subs = $this->mongo->selectCollection('SmsSubscriptions'); 
    $activeSubsctiptions = $subs->find(array('Status' => 1, '$where' => "this.SubscriptionPayments < this.SubscriptionTotal")); 
    foreach ($activeSubsctiptions AS $sub){ 
     $outstandingAmount += $sub['SubscriptionTotal'] - $sub['SubscriptionPayments']; 
    } 

    return $outstandingAmount; 
} 

现在有没有一种方法可以使用MongoDB的aggregate方法计算两个字段的差值之和?有没有其他更有效的方式来做到这一点?

回答

2

聚集的做法应该有这样的管道:

db.SmsSubscriptions.aggregate([ 
    { 
     "$project": { 
      "outstandingAmount": { 
       "$subtract": ["$SubscriptionTotal", "$SubscriptionPayments"] 
      }, 
      "Status": 1 
     } 
    }, 
    { "$match": { "Status": 1, "outstandingAmount": { "$gt": 0 } } }, 
    { 
     "$group": { 
      "_id": null, 
      "totalOutstandingAmount": { "$sum": "$outstandingAmount" } 
     } 
    } 
]) 

等价的PHP示例实现:

$ops = array(
    array(
     "$project" => array(
      "Status" => 1, 
      "outstandingAmount" => array(    
       "$subtract" => array("$SubscriptionTotal", "$SubscriptionPayments") 
       ) 
      )   
     ) 
    ), 
    array( 
     "$match" => array( 
      "Status" => 1, 
      "outstandingAmount" => array("$gt" => 0) 
     ) 
    ), 
    array(
     "$group" => array(
      "_id" => null, 
      "totalOutstandingAmount" => array("$sum" => "$outstandingAmount") 
     ) 
    ) 
); 
$results = $this->mongo->selectCollection('SmsSubscriptions')->aggregate($ops); 
+0

完美的作品。我想知道如何使这项工作,如果一个或两个'$减'字段是字符串? – eNeMetcH

+1

唯一不幸的部分是'$ subtract'对于字符串不能很好地工作,因为只要它们解析为数字和/或日期,操作符的参数可以是任何有效的表达式。所以你需要一个机制来将字符串转换为一些数字表示。 – chridam

相关问题