THpubs
THpubs

Reputation: 8172

How to combine both $group and $or in mongo and group records which have a value in one field or another together?

I'm trying to build a user messaging system and need some help. My collection looks like this :

{
  authorId: String,
  recipientId: String,
  message: String
}

What I want to do is take all the messages which have the current user's userId in either authorId or recipientId and group them. Can I do this using a mongo aggregation?

Upvotes: 0

Views: 84

Answers (2)

s7vr
s7vr

Reputation: 75934

You can try below aggregation. $group by null to push all messages.

db.message.aggregate([{
    $match: {
        $or: [{
            authorId: "someid"
        }, {
            recipientId: "someid"
        }]
    }
}, {
    $group: {
        _id: null,
        messages: {
            $push: "$message"
        }
    }
}])

Upvotes: 1

Rahul Kumar
Rahul Kumar

Reputation: 2831

maybe you can try it with $cond in projection

db.message.aggregate([
              {
                 $match : {$or : [{authorId:'1234'},{recipientId:'1234'}]}
              },
              {
                 $project : {
                    message : 1,
                    userId : {$cond : {if : {'$authorId':'1234'},'$authorId','$recepientId'}}
                 }
              },
              {
                 $group : {
                     _id : '$userId',
                     messages : {$push : '$message'}
                    }
              }
])

Upvotes: 0

Related Questions