我已经有了一个解决方案,但我正在寻找能够完成MongoServer所有工作的解决方案(因为我认为它更快,内存消耗更少)
我有一个类方法,如:
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
方法计算两个字段的差异总和?还有其他更有效的方法吗?
答案 0 :(得分:2)
聚合方法应该有这个管道:
Item Code, Product Name, and Quantity
等效的PHP示例实现:
public void showButtonSave()
{
if ((!String.IsNullOrEmpty(txtItem.Text) && !String.IsNullOrEmpty(txtProduct.Text) && !String.IsNullOrEmpty(txtQuantity.Text))
|| (!String.IsNullOrEmpty(txtItem2.Text) && !String.IsNullOrEmpty(txtProduct2.Text) && !String.IsNullOrEmpty(txtQuantity2.Text))
|| (!String.IsNullOrEmpty(txtItem3.Text) && !String.IsNullOrEmpty(txtProduct3.Text) && !String.IsNullOrEmpty(txtQuantity3.Text))
|| (!String.IsNullOrEmpty(txtItem4.Text) && !String.IsNullOrEmpty(txtProduct4.Text) && !String.IsNullOrEmpty(txtQuantity4.Text))
|| (!String.IsNullOrEmpty(txtItem5.Text) && !String.IsNullOrEmpty(txtProduct5.Text) && !String.IsNullOrEmpty(txtQuantity5.Text))
|| (!String.IsNullOrEmpty(txtItem6.Text) && !String.IsNullOrEmpty(txtProduct6.Text) && !String.IsNullOrEmpty(txtQuantity6.Text))
|| (!String.IsNullOrEmpty(txtItem7.Text) && !String.IsNullOrEmpty(txtProduct7.Text) && !String.IsNullOrEmpty(txtQuantity7.Text))
|| (!String.IsNullOrEmpty(txtItem8.Text) && !String.IsNullOrEmpty(txtProduct8.Text) && !String.IsNullOrEmpty(txtQuantity8.Text))
|| (!String.IsNullOrEmpty(txtItem9.Text) && !String.IsNullOrEmpty(txtProduct9.Text) && !String.IsNullOrEmpty(txtQuantity9.Text))
|| (!String.IsNullOrEmpty(txtItem10.Text) && !String.IsNullOrEmpty(txtProduct10.Text) && !String.IsNullOrEmpty(txtQuantity10.Text)))
{
btnAdd.Enabled = true;
}
else
{
btnAdd.Enabled = false;
}
答案 1 :(得分:0)
获得差值总和的通用简单紧凑型解决方案
collectionX
{ _id: 'xxxx', itemOne: 100, itemTwo: 300 }
{ _id: 'yyyy', itemOne: 200, itemTwo: 800 }
{ _id: 'zzzz', itemOne: 50, itemTwo: 400 }
汇总操作
db.collectionX.aggregate([
{
$group: {
_id: null,
sumOfDifferences: { $sum: { $subtract: ['$itemTwo', '$itemOne']}
}
])
响应
{
"_id" : null,
"sumOfDifferences" : 1150
}