Reputation: 8172
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
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
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