【发布时间】:2021-05-13 13:39:34
【问题描述】:
我在 MongoDb 中有一个产品集合,其中只有 _id、category、user_id 等字段。 我想检查和计算集合中每个类别的总和,给定匹配的 user_id,然后在最后再次总结所有计数。
我的解决方案是:
return Product.aggregate([
{ $match: { "user_id": "id if user that added the product" } },
{ "$unwind": "$category" },
{
"$group": {
"_id": {
'category': '$category',
},
"count": { "$sum": 1 }
}
},
{ "$sort": { "_id.category": 1 } },
{
"$group": {
"_id": "$_id.category",
"count": { "$first": "$count" }
}
}
])
代码给了我每个类别的计数,但不匹配 user_id 的条件。但是当我添加 $match 时它失败了。
产品架构:
const ProductSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
quantity: {
type: Number,
default: -1
},
category:
{
type: String,
required: true
},
manufactured_by: {
type: String,
required: true
},
user_id: {
type: Schema.Types.ObjectId,
ref: 'user',
required: true
}
})
如果我不添加条件,我的结果:
[
{
"_id": "A Tables",
"count": 1
},
{
"_id": "C Tables",
"count": 4
},
{
"_id": "B Tables",
"count": 2
}
]
【问题讨论】:
-
您可以在问题中添加示例输入数据和输出数据吗?
-
我添加了输出,我提到了操作所需的输入字段。
-
主要数据是什么?添加主要数据
-
我添加了产品架构。我不知道你问原始数据是什么意思
-
运行查询的示例文档,转到数据库并复制一些文档
标签: node.js mongodb mongoose aggregation-framework