Mysql联合查询MongoDB代码

Mysql联合查询MongoDB代码,mongodb,mongodb-query,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; 请帮忙。提前谢谢 已检查上述url。。但我的问题与此略有不同 我想得到两个集合中两个不同字段的总和 字段1-计数 字段2-数量 例如: Table 1: sno

我正在处理MongoDB代码,我需要将下面的mysql代码转换为MonogDB代码

select sum(count) as total from table1 group by month 

UNION

select sum(quantity) as total from table2 group by month;
请帮忙。提前谢谢

已检查上述url。。但我的问题与此略有不同

我想得到两个集合中两个不同字段的总和

  • 字段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
    }
    

    感谢您的回复。。在上面加上我的解释。。你能帮个忙吗..你可能可以用这样的东西来聚合-
    db.table1.aggregate([{$group:{id:{month],total:{$sum:$count}}}])
    &
    db.table1.aggregate([{$group:{id:{month],total:{$sum:$quantity}}])
    。可能使用
    $out
    将结果保存到新集合中&执行类似于SQL中的Union的操作