MongoDB汇总不同文档中数组中的项目总数?

编程入门 行业动态 更新时间:2024-10-23 08:28:53
本文介绍了MongoDB汇总不同文档中数组中的项目总数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的MongoDB收集模式:

Here is my MongoDB collection schema:

company: String model: String tags: [String]

我需要对其进行汇总,以便获得以下输出:

I need to aggregate it so I get the following output:

[{ "_id": { "company": "Lenovo", "model": "T400" }, "tags": { tag: "SomeTag" count: 124 // number of times, this tag was found in `Lenovo T400` } }...]

我尝试执行以下操作:

var aggParams = {}; aggParams.push({ $unwind: '$tags' }); aggParams.push({ $group: { _id: { company: '$company', model: '$model' }, tags: { $push: { tag: '$tags', count: { $sum: 1 } } }, }});

但是我遇到了以下错误:

But I got the following error:

invalid operator '$sum'

用aggregation执行此操作的正确方法是什么?

What is the right way to do this with aggregation?

推荐答案

您需要处理 $unwind 以便在聚合中有意义地处理它.另外,您要添加到数组中并计数"一个单独的阶段.以及参数本身的数组"中的聚合管道,而不是您定义的对象:

You need to process $unwind on an array in order to deal with it meaninfully in aggregation. Also you adding to an array and "counts" stage a separate. As well an aggregation pipeline in an "array" of arguments itself, and not an object as you have defined:

Model.aggregate([ { "$unwind": "$tags" }, { "$group": { "_id": { "company": "$company", "model": "$model", "tag": "$tags" }, "count": { "$sum": 1 } }}, { "$group": { "_id": { "company": "$_idpany", "model": "$_id.model", }, "tags": { "$push": { "tag": "$_id.tag", "count": "$count" } }} ], function(err,result) { })

所以有两个 $group 阶段在这里完成工作.一种是对公司和模型中的标签进行汇总,另一种是仅对公司"和模型"进行分组,然后将不同的标签和计数添加到数组中.

So two $group stages does the job here. One to sum up the tags within company and model and the other to group on just the "company" and "model" and add the distinct tags and counts to an array.

更多推荐

MongoDB汇总不同文档中数组中的项目总数?

本文发布于:2023-11-22 19:32:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   总数   中数   文档   项目

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!