Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongo aggregate group by pair

I have collection like this

User Receiver IsRead
A B false
B A false
A B false
A C false
C A false

How can I group it by both User and Receiver to get result like this

Combined Field Messages
AB OR BA 3
AC OR CA 2

tried this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$group: {
    _id: {$or: [{userId: "$recipientId", recipientId: "$userId"}, {userId: "$userId", recipientId: "$recipientId"}]},
    messages: {$sum: {$cond: [{$eq: ['$isRead', false]}, 1, 0]}} // count
}

>Solution :

You can set the $group key to be $setUnion of the User and Receiver field.

db.collection.aggregate([
  {
    $group: {
      _id: {
        "$setUnion": [
          [
            "$User"
          ],
          [
            "$Receiver"
          ]
        ]
      },
      "Messages": {
        $sum: {
          "$cond": {
            "if": {
              $not: "$IsRead"
            },
            "then": 1,
            "else": 0
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading