【问题标题】:Count by category and sum it up in MongoDB按类别计数并在MongoDB中总结
【发布时间】:2021-05-13 13:39:34
【问题描述】:

我在 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.js mongodb mongoose aggregation-framework


【解决方案1】:

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

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

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

【讨论】:

  • 集合中有很多用户添加的产品。我想根据给定的 user_id 计算类别。
  • 我的例子应该这样做
  • 它给了我空的结果。
  • 再看看产品架构。
  • 您是否正确提供了作为 ObjectId 的 Seller_id?
猜你喜欢
  • 1970-01-01
  • 2021-11-08
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
相关资源
最近更新 更多