【发布时间】:2022-01-08 10:14:10
【问题描述】:
您好,我正在为使用 MEAN 堆栈销售的产品创建一个新的 Web 应用程序,我想查看每个品牌(HP、ASUS ..)有多少台电脑有 8 Gb,有多少台电脑有 4 GB 等。 这是我的代码
exports.allcountProduct = async (req, res) => {
try {
const count = await Product.aggregate(
{
"$group": {
"_id": {
$toLower: "$ram"
},
"count": { "$sum": 1 }
}
},
{
"$group": {
"_id": null,
"counts": { "$push": { "k": "$_id", "v": "$count" } }
}
},
{
"$replaceRoot": {
"newRoot": { "$arrayToObject": "$counts" }
}
},
],
)
res.json(count);
}
我得到的是:
[
{
"4GB": 20,
"8GB": 15,
"16GB": 32
}
]
所以我得到的是所有品牌的结果,而我试图得到的是每个品牌都像这样:
[
{
"brand": "ASUS",
"8GB": 6,
"16GB": 14
}
]
这是文档中的一个示例:
{
"_id":ObjectID( "617b0dbacda6cbd1a0403f68")
"brand": "6178524a5ff14e633aeff1ea",
"SerialNumber": "45454234324",
"ram": "4gb",
},
{
"_id":ObjectID( "617b0dbacda6cbd1a040345")
"brand": "6178524a5ff14e633aeff1ea",
"SerialNumber": "azazz5245454az",
"ram": "8gb",
},
【问题讨论】:
-
如果您添加原始文档结构会有所帮助,因为不清楚品牌所在的位置...
-
@R2D2
{ "_id":ObjectID( "617b0dbacda6cbd1a0403f68") "brand": "6178524a5ff14e633aeff1ea", "SerialNumber": "45454234324", "ram": "4gb", }, { "_id":ObjectID( "617b0dbacda6cbd1a040345") "brand": "6178524a5ff14e633aeff1ea", "SerialNumber": "azazz5245454az", "ram": "8gb", },
标签: node.js mongodb mongodb-query aggregation-framework aggregate-functions