我有一个看起来像这样的集合:
{
"id": "id1",
"tags": ['a', 'b']
},
{
"id": "id2",
"tags": ['b', 'c']
},
{
"id": "id3",
"tags": ['a', 'c']
}
如何进行按“tags”数组中的每个元素进行分组的查询,以便结果如下所示?:
{'a': 2},
{'b': 2},
{'c': 2}
(其中2是它出现的次数,即计数)。
感谢您的帮助!
您可以使用此聚合查询:
- First
$unwind
数组解构访问类似对象。
- Then
$group
by tags
and $sum
1 得到总数。
- 以及最后一次使用
$replaceRoot
with $arrayToObject
以获得所需的输出。
db.collection.aggregate([
{
"$unwind": "$tags"
},
{
"$group": {
"_id": "$tags",
"count": {
"$sum": 1
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": [
[
{
"k": "$_id",
"v": "$count"
}
]
]
}
}
}
])
Example here https://mongoplayground.net/p/GmF7y9zr0en
作为补充,如果您想获取排序值(a,b,c ...),您可以添加$sort
舞台般这个例子 https://mongoplayground.net/p/CTFOGLCJBNw
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)