Mysql Union查询到MongoDB代码

时间:2016-07-12 13:36:35

标签: mongodb mongodb-query

我正在研究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. Field1 - count
  2. Field2 - 数量
  3. 示例:

    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
    

    我希望这个结果在单个字段中。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

在这里,我找到了 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
}