首页 > 解决方案 > MongoDB中的$subtract聚合操作导致页面不加载

问题描述

我对javascript很陌生。我正在尝试为网站创建仪表板。我希望仪表板显示有多少订单未完成。我能够显示已完成的订单,但是当我尝试使用 $subtract 通过从订单总数中减去已完成的数量来获取未完成的订单时,我的页面不再加载。我非常感谢有关此问题的任何帮助或指导。谢谢你。

我的未完成订单代码:

  const unfullfilled = await Order.aggregate([
      {
        $group: {
          _id: null,
          fullfill: { $sum: '$shippedValue' },
          orders: { $sum: 1 },
          unfullfill: {$subtract:['$orders','$fullfill']},
        },
      },
    ]);

仪表板显示部分:

<li>
   <div className="summary-title color2">
      <span>
        <i className="fa fa-shopping-cart" />Unfullfilled
      </span>
   </div>
   <div className="summary-body">
     {summary.unfullfilled[0] ? summary.unfullfilled[0].unfullfill : 0}
   </div>
</li>

我的完整订单代码:

 const fullfilled = await Order.aggregate([
      {
        $group: {
          _id: null,
          fullfill: { $sum: '$shippedValue' },
        },
      },
    ]);

仪表板显示部分:

<li>
       <div className="summary-title color2">
          <span>
            <i className="fa fa-shopping-cart" />Fullfilled
          </span>
       </div>
       <div className="summary-body">
          {summary.fullfilled[0] ? summary.fullfilled[0].fullfill : 0}
       </div>
</li>

标签: javascriptmongodbaggregation-framework

解决方案


您不能使用$subtractwith $groupas $subtractis not a accumulator 运算符。

你可以使用$project舞台

 const unfullfilled = await Order.aggregate([
      {
        $group: {
          _id: null,
          fullfill: { $sum: '$shippedValue' },
          orders: { $sum: 1 }
        },
      },
      {
        $project:{
          fullfill:1,
          orders:1,
          unfullfill: {$subtract:['$orders','$fullfill']}
        }
      }
    ]);

推荐阅读