我有以下文件:
{
"src": "value",
"dst": "value",
"subject": "value"
}
我的第一个目标是按src
和dst
字段汇总它们,并获取与元组相关联的subject
src
,dst
) 。这是我的疑问:
db.mycollection.aggreate([
{
"$group": {
"_id": {
"src": "$src",
"dst": "$dst"
},
"subjects": {
"$push": "$subject"
}
}
}
])
感谢此查询,我得到subject
和src
的每dst
个[
{
"src": "distinct src",
"dst": "distinct dst",
"subjects": [
{
"distinct subject",
"distinct subject",
"distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject"
"another distinct subject"
]
},
{
"src": "another distinct src",
"dst": "another distinct dst",
"subjects": [
"distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject",
"another distinct subject"
]
}
]
。这是预期的结果:
subject
下一步是:我如何对这些[
{
"src": "distinct src",
"dst": "distinct dst",
"subjects": [
{
"subject": "distinct subject",
"count": 3
},
{
"subject": "another distinct subject",
"count": 5
}
},
{
"src": "another distinct src",
"dst": "another distinct dst",
"subjects": [
{
"subject": "distinct subject",
"count": 1
},
{
"subject": "another distinct subject",
"count": 11
}
}
]
进行分组,以便我可以拥有一个可以计算这些主题的字段?我的意思是,我希望得到一个结果:
{{1}}
我不知道这是否可能,因为我对mongodb很新;如果有人有任何线索,我会非常感激。
答案 0 :(得分:1)
为了达到最终结果,我认为你应该首先考虑每个主题。以下供您参考:
db.collection.aggregate([{
$group : {
_id : {
src : "$src",
dst : "$dst",
subject : "$subject"
},
count : {
$sum : 1
}
}
}, {
$group : {
_id : {
src : "$_id.src",
dst : "$_id.dst"
},
subjects : {
$push : {
subject : "$_id.subject",
count : "$count"
}
}
}
}, {
$project : {
_id : 0,
src : "$_id.src",
dst : "$_id.dst",
subjects : "$subjects"
}
}]);