MongoDB 为每个数组元素计数文档 [英] MongoDB count documents for each array elements

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

问题描述

我是

{
  code : "X1",
  elements : ["A", "B", "C", "D"]
},
{
  code : "X2",
  elements : ["C", "D"]
},
{
  code : "X3",
  elements : ["A"]
}
...

我想知道元素"数组中每种类型的值存在的文档数.es.

I would like to know the number of documents present for each type of value in the "elements" array. es. es.

"A" : 2
"B" : 1
"C" : 2
"D" : 2

是否可以使用单个查询?

is it possible with a single query?

推荐答案

您可以 $unwind 您的数组以获取每个元素的单个文档,然后运行 ​​$group 计算元素:

You can $unwind your array to get single document per element and then run $group to count elements:

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

您可以使用附加组 $replaceRoot$arrayToObject 返回您的 ID作为键并计为值:

you can use additional group with $replaceRoot and $arrayToObject to return your ids as keys and counts as values:

db.collection.aggregate([
    {
        $unwind: "$elements"
    },
    {
        $group: {
            _id: "$elements",
            count: { $sum: 1 }
        }
    },
    {
        $group: {
            _id: null,
            counts: { $push: { k: "$_id", v: "$count" } }
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$counts" }
        }
    }
])

蒙戈游乐场

这篇关于MongoDB 为每个数组元素计数文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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