我有这些文件:
[
{
"question": 1,
"answer": "Foo"
},
{
"question": 1,
"answer": "Foo"
},
{
"question": 1,
"answer": "Bar"
},
{
"question": 2,
"answer": "Foo"
},
{
"question": 2,
"answer": "Foobar"
}
]
在我的后端(php)中,我需要重新分配答案,例如:
问题1:
问题2:
现在我只想运行一个mongo查询来实现这个结果:
[
{
"question": 1,
"answers": {
"Foo": 2,
"Bar": 1
}
},
{
"question": 2,
"answers": {
"Foo": 1,
"Foobar": 1
}
}
]
以下是我提出的建议:
db.getCollection('testAggregate').aggregate([{
$group: {
'_id': '$question',
'answers': {'$push': '$answer'},
}
}
]);
它返回:
{
"_id" : 2.0,
"answers" : [
"Foo",
"Foobar"
]
},{
"_id" : 1.0,
"answers" : [
"Foo",
"Foo",
"Bar"
]
}
现在我需要对答案字段进行$ group操作以计算出现的次数,但我需要保持该组的问题并且我不知道该怎么做。有人可以帮我一把吗?
答案 0 :(得分:1)
您可以使用以下聚合。
按问题和答案分组以获得组合计数,然后按组提问以获得答案及其计数。
db.getCollection('testAggregate').aggregate([
{"$group":{
"_id":{"question":"$question","answer":"$answer"},
"count":{"$sum":1}
}},
{"$group":{
"_id":"$_id.question",
"answers":{"$push":{"answer":"$_id.answer","count":"$count"}}
}}
]);
您可以使用以下代码在3.4中获取所需的格式。
将$group
键更改为k和v,然后将$addFields
更改为$arrayToObject
,将数组转换为命名键值对。
db.getCollection('testAggregate').aggregate([
{"$group":{
"_id":{"question":"$question","answer":"$answer"},
"count":{"$sum":1}
}},
{"$group":{
"_id":"$_id.question",
"answers":{"$push":{"k":"$_id.answer","v":"$count"}}
}},
{"$addFields":{"answers":{"$arrayToObject":"$answers"}}}
]);