Mongoose 聚合按brand_id 和orders_sum > 1000 进行分组

问题描述 投票:0回答:1

Sales
集合中,我试图获取按
brand_id
分组的所有文档,并且每个品牌的总订单价值大于 1000 美元。

那么如果有A、B、C、D品牌。然后它应该记录每个品牌的 Sales 集合,其中该品牌的总销售额高于 1000 美元。

我用于获取按

brand_id
分组的文档的代码是:

const data = await Sales.aggregate([
    {
      $group: {
        _id: '$brand_id',
        records: {
            $push: "$$ROOT"
        }
      }
    }
]);

但是我很困惑如何添加仅当每个品牌销售额总额超过 1000 美元时才获取文档的条件。

我尝试检查 Mongoose 的文档,但我不知道如何在

aggregate()

上添加条件
node.js mongodb mongoose mongoose-populate
1个回答
0
投票

方法1

  1. $group
    - 按
    brand_id
    分组并对
    order
    /
    price
    字段 (
    total_sales
    ) 执行求和。

  2. $match
    - 使用
    total_sales
    大于 1000 来过滤文档。

  3. $unwind
    - 将
    records
    数组解构为多个文档。

  4. $replaceWith
    - 用原始销售单据替换输入单据。

const data = await Sales.aggregate.aggregate([
  {
    $group: {
      _id: "$brand_id",
      total_sales: {
        $sum: "$price"
      },
      records: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $match: {
      total_sales: {
        $gt: 1000
      }
    }
  },
  {
    $unwind: "$records"
  },
  {
    $replaceWith: "$records"
  }
])

演示方法 1 @ Mongo Playground


方法2

  1. $setWindowFields
    - 允许在每个文档中通过
    order
    (
    price
    ) 对
    brand_id
    /
    total_sales_by_brand
    执行求和的替代方法。

  2. $match
    - 使用
    total_sales_by_brand
    大于 1000 来过滤文档。

  3. $unset
    (可选)- 删除
    total_sales_by_brand
    字段。

db.collection.aggregate([
  {
    $setWindowFields: {
      partitionBy: "$brand_id",
      sortBy: {},
      output: {
        total_sales_by_brand: {
          $sum: "$price"
        }
      }
    }
  },
  {
    $match: {
      total_sales_by_brand: {
        $gt: 1000
      }
    }
  },
  {
    $unset: "total_sales_by_brand"
  }
])

演示方法 2 @ Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.