I have a schema representing a message thread. So each document in the mongo database looks something like:
{
id: "thread_id",
participants: ["user1", "user2"],
unReadMessageCounts: [
{
participant: "user1",
count: 5
},
{
participant: "user2",
count: 3
}
}
What I want to do is get a sum of all unread messages counts for a given user - say, "user2". I know I could do this by just doing a find()
on the collection and then writing a function to sum up to counts for a given user. But I'd like to use mongo's aggregate
functionality if possible. I know I can do a match
to first select all threads in which "user2" is a participant, but then how do I construct the group
and/or sum
expressions to pull out the right field from the document?