繁体   English   中英

按类别统计,总结在MongoDB

[英]Count by category and sum it up in 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
    }
]

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

但以下应该给你想要的 output (没有你添加的任何并发症)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM