node.js - 按类别计数并在MongoDB中总结
问题描述
我在 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
}
]
解决方案
不确定您要从管道的最后阶段实现什么。
但是以下应该会给你想要的输出(没有你添加的任何复杂性)
async getSellerStatistics(seller_id) {
return await Product.aggregate([
{ $match: { user_id: seller_id } }
{ $unwind: "$category" },
{
$group: {
_id: "$category",
count: { $sum: 1 },
},
},
{ $sort: { _id: 1 } },
])
}
推荐阅读
- java - java.lang.outofmemoryerror 与 firebase 更新
- flutter - 颤振依赖错误
- excel - 根据所选值禁用或启用字段
- sas - 使用 SAS EG 获取百分比
- python - Python 3.6 没有名为 ... 在 windows Server 2008 R2 上的模块
- xamarin - Xamarin Forms 中的部分屏幕页面
- stripe-payments - 尝试获取 Stripe Token 时出错
- javascript - ajax功能完成后socket.io连接
- sql-server - SSRS 中个人姓名的单独图表
- reactjs - 在 RxJS 或 Redux Observable 中 debounceTime 也起到延迟的作用