我有一个具有以下结构的集合
{
"_id" : "000aaa111",
"reviewer_id" : "KQ5E8vKN5ezzgwH3C",
"reviewee_id" : "FodX5fCg3RBe92Dpu",
"stars" : [
{
"val" : "4.5",
"for" : "communication"
},
{
"val" : "4",
"for" : "cleanliness"
}
]
}
这实际上是为我的访问者给他们明星(1到5)的项目评分。那么我如何能够汇总我在集合中的所有文档来总结收到的所有明星。这是我期望的输出
{
"reviewee_id": "FodX5fCg3RBe92Dpu",
"overall": "5",
"communication": "3",
"cleanliness": "3.5"
}
Mongodb对我来说还是一个新手,我找不到任何与我现在的结构相匹配的例子。
你认为我的好去吗?
答案 0 :(得分:0)
根据预期的输出,您需要调整结构以充分利用聚合。
你的结构应该是这样的。
<强>输入:强>
{
"_id": ObjectId("585dc520772c68234445f2a4"),
"reviewer_id": "KQ5E8vKN5ezzgwH3C",
"reviewee_id": "FodX5fCg3RBe92Dpu",
"stars": [{
"communication": 4.5
}, {
"cleanliness": 4
}, {
"overall": 3
}]
} {
"_id": ObjectId("585dc520772c68234445f2a2"),
"reviewer_id": "KQ5E8vKN5ezzgwH3D",
"reviewee_id": "FodX5fCg3RBe92Dpu",
"stars": [{
"communication": 2.5
}, {
"cleanliness": 3
}, {
"overall": 4
}]
}
<强>查询:强>
aggregate(
[{
$unwind: "$stars"
}, {
$group: {
_id: "$reviewee_id",
communication: {
$avg: "$stars.communication"
},
cleanliness: {
$avg: "$stars.cleanliness"
},
overall: {
$avg: "$stars.overall"
}
}
}]
)
<强>输出强>
{ "_id" : "FodX5fCg3RBe92Dpu", "communication" : 3.5, "cleanliness" : 3.5, "overall" : 3.5 }