假设在 mongo 中我有一个如下所示的集合:
+----+-----+-----+----------+
| id | x | y | quantity |
+----+-----+-----+----------+
| 1 | abc | jkl | 5 |
+----+-----+-----+----------+
| 2 | jkl | xyz | 10 |
+----+-----+-----+----------+
| 3 | xyz | abc | 20 |
+----+-----+-----+----------+
我想做一个 $group,其中 x 等于 y 并对数量求和。所以输出看起来像:
+-----+-------+
| x | total |
+-----+-------+
| abc | 25 |
+-----+-------+
| jkl | 15 |
+-----+-------+
| xyz | 30 |
+-----+-------+
这可以在 mongo 中完成吗?
最佳答案
您不会执行 $group 来检索结果。您正在执行$lookup 。此功能是 MongoDB 3.2 中的新增功能。
使用您提供的示例数据,聚合如下:
db.join.aggregate( [
{
"$lookup" : {
"from" : "join",
"localField" : "x",
"foreignField" : "y",
"as" : "matching_field"
}
},
{
"$unwind" : "$matching_field"
},
{
"$project" : {
"_id" : 0,
"x" : 1,
"total" : { "$sum" : [ "$quantity", "$matching_field.quantity"]}
}
}
])
示例数据集非常简单,因此您需要测试当返回的值不仅仅是一个简单结果等时的行为。
编辑:
如果 X 和 Y 之间可以有多个匹配,事情就会变得更加复杂。
// Add document to return more than a single match for abc
db.join.insert( { "x" : "123", "y" : "abc", "quantity" : 100 })
// Had to add $group stage to consolidate matched results
db.join.aggregate( [
{
"$lookup" : {
"from" : "join",
"localField" : "x",
"foreignField" : "y",
"as" : "matching_field"
}
},
{
"$unwind" : "$matching_field"
},
{ "$group" : {
"_id" : { "x" : "$x", "quantity" : "$quantity" },
"matched_quantities" : { "$sum" : "$matching_field.quantity" }
}},
{
"$project" : {
"x" : "$_id.x",
"total" : { "$sum" : [ "$_id.quantity", "$matched_quantities" ]}
}
}
])
关于mongodb - Mongo 中的两列分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399395/