MongoDB按数组中的元素分组 [英] MongoDB group by elements in array
本文介绍了MongoDB按数组中的元素分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的集合:
I have a collection that looks like this:
{
"id": "id1",
"tags": ['a', 'b']
},
{
"id": "id2",
"tags": ['b', 'c']
},
{
"id": "id3",
"tags": ['a', 'c']
}
如何进行按标签"中的每个元素分组的查询?数组,所以结果看起来像这样?:
How can I make a query that groups by every element in the "tags" array, so the result looks like this?:
{'a': 2},
{'b': 2},
{'c': 2}
(其中 2 是出现的次数,计数).感谢您的帮助!
(where 2 is the number of times it appears, the count). Thanks for your help!
推荐答案
你可以使用这个聚合查询:
You can use this aggregation query:
- 首先
$unwind
数组来解构像对象一样的访问. - 然后
$group
通过tags
和$sum
1 得到总数. - 最后使用
$replaceRoot
和$arrayToObject
来获得所需的输出.
- First
$unwind
the array to deconstruct an access like objects. - Then
$group
bytags
and$sum
1 to get the total. - And last use
$replaceRoot
with$arrayToObject
to get the desired output.
db.collection.aggregate([
{
"$unwind": "$tags"
},
{
"$group": {
"_id": "$tags",
"count": {
"$sum": 1
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": [
[
{
"k": "$_id",
"v": "$count"
}
]
]
}
}
}
])
示例此处
作为补充,如果您想获得排序值(a、b、c...),您可以添加 $sort
阶段,如 这个例子
As an adittion, if you want to get sorted values (a, b, c...) you can add $sort
stage like this example
这篇关于MongoDB按数组中的元素分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文