mongodb - 获取每个类别销售的产品总量的有效方法
问题描述
我有一个问题如下。我需要获取每个类别的销售产品总量。一个产品可以属于多个类别。一个类别还可以在一个类别中包含多个产品。我有以下方案:
//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 上找不到解决方案。感谢您的回答!
解决方案
在管道阶段之后添加以下阶段,
$unwind
解构cat
数组以创建对象$unwind
解构p
数组以生成和对象$group
按类别名称和计数所需的统计信息
{ $unwind: "$cat" },
{ $unwind: "$p" },
{
$group: {
_id: "$cat.name",
totalPrice: { $sum: "$price" },
qty: { $sum: "$quantity" },
totalSold: { $sum: 1 }
}
}
您确实需要将架构更改为现代架构,这种结构不适合 mongo 数据库。
推荐阅读
- apache-spark - 如何在pyspark中以毫秒为单位指定窗口大小?
- android - 添加 Zoom Android SDK 后,有什么方法可以将 APK 大小减少到 5-10 MB 以内?
- javascript - SyntaxError:无法在模块外部使用导入语句 - vue electron builder plugin
- angular - 如何检测何时完成一系列操作
- azure - 如果在 Azure 数据工厂的上一个活动中未复制任何文件,则防止触发下一个活动
- java - 在 SimpleDateFormat 上使用 DateTimeFormatter
- sql - 从工作 SQL 表映射多个布局 - SSIS
- python - 正则表达式替换全名python
- python - Tkinter 使用循环创建按钮并从维度列表写入按钮
- google-cloud-recommendation - 有什么方法可以终止用户事件导入批量加载作业