MongoDB计算数组中的项目 [英] MongoDB count items in array

查看:75
本文介绍了MongoDB计算数组中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个集合,如下所示

Let's say we have a collection as follows

{ "_id" : 1, "item" : "ABC", "sizes": [ "S", "M", "L"] },
{ "_id" : 2, "item" : "EFG", "sizes": [ "S" ] },
{ "_id" : 3, "item" : "ABC", "sizes": [ "M" ] }

如何列出数组中的项目(大小)以及与该大小相关的项目数量

How can we list the items in the array (sizes) and the quantity of items associated to the sizes

例如

size 'S', item 'ABC' = 1
size 'S', item 'EFG' = 1
size 'M', item 'ABC' = 2
size 'L', item 'ABC' = 1

请注意,大小 M必须适用于项目为 ABC的情况。

Note that size 'M' has to instances where item is 'ABC'.

我尝试了以下操作

db.collection.group(
{
    key: {'sizes': true}, 
    initial: {sum: 0}, 
    reduce: function(doc, prev) { prev.sum += 1}
});

但它不会展开数组,我似乎无法将Item作为一部分添加

but it doesn't unwind the array and I can not seem to able to add the Item as part of the group count

任何想法?

谢谢

推荐答案

您需要 $ unwind 然后是数组,然后 $ group 通过 item和 sizes并使用 $ sum 返回计数。

You need to $unwind the "sizes" array then $group by "item" and "sizes" and use the $sum to return the count.

db.collection.aggregate(
    [ 
        { "$unwind": "$sizes" }, 
        { "$group": { 
            "_id": { 
                "item": "$item", 
                "sizes": "$sizes" 
            }, 
            "count": { "$sum": 1 } 
        }}
    ]
) 

会产生:

{ "_id" : { "item" : "EFG", "sizes" : "S" }, "count" : 1 }
{ "_id" : { "item" : "ABC", "sizes" : "L" }, "count" : 1 }
{ "_id" : { "item" : "ABC", "sizes" : "M" }, "count" : 2 }
{ "_id" : { "item" : "ABC", "sizes" : "S" }, "count" : 1 }

这篇关于MongoDB计算数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆