首页 > 解决方案 > 按类别计数并在MongoDB中总结

问题描述

我在 MongoDb 中有一个产品集合,其中唯一的字段如_idcategoryuser_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.jsmongodbmongooseaggregation-framework

解决方案


不确定您要从管道的最后阶段实现什么。

但是以下应该会给你想要的输出(没有你添加的任何复杂性)

async getSellerStatistics(seller_id) {
    return await Product.aggregate([
        { $match: { user_id: seller_id } }
        { $unwind: "$category" },
        {
            $group: {
                _id: "$category",
                count: { $sum: 1 },
            },
        },
        { $sort: { _id: 1 } },
    ])
}

推荐阅读