I have a collection of emails:
{ "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." }
I can get the total number of emails sent by each person like this:
db.emails.aggregate({$group: {_id: "$sender", totalSent: {$sum: 1}}})
And total received like this:
db.emails.aggregate({$unwind: "$to"}, {$group: {_id: "$to", totalReceived: {$sum: 1}}})
But how do I do these together in a single query so I get this output:
{ "_id" : "tom@gmail.com", "totalReceived" : 2 }
{ "_id" : "harry@gmail.com", "totalReceived" : 1, totalSent: 1 }
{ "_id" : "bob@gmail.com", "totalReceived" : 1, totalSent: 2 }