获取每个品类销售产品总量的有效方法

时间:2021-01-11 13:59:37

标签: mongodb group-by nosql aggregation-framework lookup

我有如下问题。我需要获得每个类别销售的产品总量。一种产品可以属于多个类别。一个类别还可以在一个类别中包含多个产品。 我有以下方案:

//Categories scheme
{
  name: {
        type: String,
        required: [true, "The Category name is required"],
        unique: true,
    }}

 //Products
{
  name: {
        type: String,
        required: [true, "The prodcut name is required"],
        unique: true,
    }
    price: {
        type: mongoose.Types.Decimal128,
        default: "0.0",
    },
 }

 //Products Categories scheme
{ 
    product: {
        type: Schema.Types.ObjectId, ref: "Products",
    },
    category: {
        type: Schema.Types.ObjectId, ref: "Categories",
    },
 }
 //Orders model scheme
{ 
    product: {
        type: Schema.Types.ObjectId, ref: "Products",
    },
    price: {
        type: mongoose.Types.Decimal128,
        default: "0.0",
    },
    quantity: {
        type: Number,
        default: 0,
    }
 }

我有类似上面的方案。我尝试按如下方式创建查询,但它只需要一个产品。

OrdersModel.aggregate(
        [
            { $lookup: { from: 'products', localField: 'product', foreignField: '_id', as: 'p' } },
            { $lookup: { from: 'prodcutcategories', localField: 'p._id', foreignField: 'product', as: 'pc' } },
            { $lookup: { from: 'categories', localField: 'pc.category', foreignField: '_id', as: 'cat' } },
            {
                $group:
                {
                    _id: "$cat.name", 
                }
            },
        ]
    )

此查询有效但产生了一种产品,如下所示:

{
"status": "Success",
"data": [
    {
        "_id": [
            "A category",
            "A product"
        ]
    }
 ]
}

但我需要这样:

{
"status": "Success",
"data": [
    {
        "category": "Category name 1",
        "totalPrice": 10000,
        "qty": 10000,
        "mostSoldProduct": "Product name",
        ...
    },
    {
        "category": "Category name 2",
        "totalPrice": 10000,
        "qty": 10000,
        "mostSoldProduct": "Product name",
        ...
    }
 ]
}

我应该得到与上面相同的结果。但我说我做查询错了。 我在 MSSQL 中创建了一个类似于以下内容的查询。

select cat.name sum(o.price) from order o 
inner join products p on p.id=o.productid
inner join products_categories pc on p.id=pc.productid
inner join catrgories cat on cat.id=pc.category_id
group by cat.name

有什么方法可以解决我的问题?我在 Google 上搜索了很多,但在 MongoDB 上找不到解决方案。 感谢您的回答!

1 个答案:

答案 0 :(得分:0)

在管道阶段之后添加以下阶段,

  • $unwind 解构 cat 数组以制作对象
  • $unwind 解构 p 数组以生成和对象
  • $group 按类别名称和计数所需的统计数据
  { $unwind: "$cat" },
  { $unwind: "$p" },
  {
    $group: {
      _id: "$cat.name",
      totalPrice: { $sum: "$price" },
      qty: { $sum: "$quantity" },
      totalSold: { $sum: 1 }
    }
  }

Playground

<块引用>

您确实需要将架构更改为现代架构,这种结构不适用于 mongo 数据库。