Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB聚合-在单个查询中以两种方式分组_Mongodb_Aggregation Framework - Fatal编程技术网

MongoDB聚合-在单个查询中以两种方式分组

MongoDB聚合-在单个查询中以两种方式分组,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我收集了一些电子邮件: { "sender" : "bob@gmail.com", "to" : [ "harry@gmail.com", "tom@gmail.com" ], "text" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit." } { "sender"

我收集了一些电子邮件:

{ "sender" : "bob@gmail.com", "to" : [ "harry@gmail.com", "tom@gmail.com" ], "text" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }
{ "sender" : "bob@gmail.com", "to" : [ "tom@gmail.com" ], "text" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }
{ "sender" : "harry@gmail.com", "to" : [ "bob@gmail.com" ], "text" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }
我可以得到每个人发送的电子邮件总数,如下所示:

db.emails.aggregate({$group: {_id: "$sender", totalSent: {$sum: 1}}})
db.emails.aggregate({$unwind: "$to"}, {$group: {_id: "$to", totalReceived: {$sum: 1}}})
收到的总金额如下:

db.emails.aggregate({$group: {_id: "$sender", totalSent: {$sum: 1}}})
db.emails.aggregate({$unwind: "$to"}, {$group: {_id: "$to", totalReceived: {$sum: 1}}})
但是如何在一个查询中同时执行这些操作,从而获得以下输出:

{ "_id" : "tom@gmail.com", "totalReceived" : 2 }
{ "_id" : "harry@gmail.com", "totalReceived" : 1, totalSent: 1 }
{ "_id" : "bob@gmail.com", "totalReceived" : 1, totalSent: 2 }

有更好的选择可以做到这一点,我和大家分享的一个选择是,在处理更多文档的过程中,可能会有大量的事务

  • $facet
    要分别发送和接收两个阵列
  • $project
    使用
    $concatarray
  • $unwind
    解构
    all
    数组
  • $group
    by
    all.\u id
    表示电子邮件和获取发送和接收计数