我们说我有以下信息集:
{
"sender_id": 1,
"sender_name": "Brian",
"receiver_id": 2,
"receiver_name": "John",
"text": "Hey, John, you also have this app!"
},
{
"sender_id": 2,
"sender_name": "John",
"receiver_id": 1,
"receiver_name": "Brian",
"text": "Oh yea Brian, wazzup?"
},
{
"sender_id": 3,
"sender_name": "Jack",
"receiver_id": 2,
"receiver_name": "John",
"text": "Hey John!"
}
...
我想使用MongoDB聚合框架将这些消息合并到对话框/对话中。让我们说,我想要获取 John (id = 2)参与的所有对话:
{
"other_participant_id": 1,
"other_participant_name": "Brian",
"last_message": "Oh yea Brian, wazzup?",
"count": 2
},
{
"other_participant_id": 3,
"other_participant_name": "Jack",
"last_message": "Hey John!",
"count": 1
},
我发现实现此目的的一种方法是获取第一个参与者的ID并使用$cond
确定在分组时是否应使用sender_id
或receiver_id
:
// Let's say we are building this for John, with id=2
db.messages.aggregate(
[
{
$match: {
$or: [
{receiver_id: 2},
{sender_id: 2}
]
},
},
{
$sort:{ date: 1 }
},
{
$group:{
_id: { other_participant_id: { $cond: [{$eq:["$sender_id", 2]}, "$receiver_id", "$sender_id"] } },
other_participant_id: { $last: { $cond: [{$eq:["$sender_id", 2]}, "$receiver_id", "$sender_id"] } },
other_participant_name: { $last: { $cond: [{$eq:["$sender_id", 2]}, "$receiver_name", "$sender_name"] } },
last_message: { $last: "$text" },
count: { $sum: 1 }
}
}
]
);
这似乎有效,但我觉得这很难看。 有没有更好的或'#34;对"实现这个目标的方法?