我正在处理MongoDB代码,我需要将以下mysql代码转换为MonogDB代码
select sum(count) as total from table1 group by month
UNION
select sum(quantity) as total from table2 group by month;
请帮忙。提前感谢!
检查了上面的网址..但我的问题与此略有不同。
我想获取两个集合中两个不同字段的总和。
- 字段 1 - 计数
- 字段 2 - 数量
例:
Table 1:
sno count month
1 20 3
2 50 5
3 70 7
Table 2:
sno quantity month
1 10 3
2 20 6
3 30 7
我想要如下结果,
month Total
3 30
7 100
我希望在单个字段中获得此结果。我该怎么做?
在这里,我找到了MongoDB聚合的解决方案。
db.getCollection('table1').aggregate([
{$lookup : { from : "table2",localField : "month", foreignField :"month", as:"table2"}},
{$unwind : "$table2"},
{
$group : {
_id : {
month :"$month",
},
total : { $sum : { $add: [ "$count", "$table2.quantity" ] }}
}
},
{$sort : {"_id.month":1}},
{
$project : {
month :"$_id.month",
total : 1,
_id : 0
}
}
])
下面是我期望的输出。
{
"total" : 30,
"month" : 3
}
{
"total" : 100,
"month" : 7
}