【发布时间】:2021-01-11 13:59:37
【问题描述】:
我有一个问题如下。我需要获取每个类别的销售产品总量。一个产品可以属于多个类别。一个类别还可以在一个类别中包含多个产品。 我有以下方案:
//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 上找不到解决方案。 感谢您的回答!
【问题讨论】:
标签: mongodb group-by nosql aggregation-framework lookup