使用Mongodb聚合框架将消息分组到对话中

时间:2017-06-26 00:05:34

标签: mongodb aggregation-framework

我们说我有以下信息集:

{
    "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_idreceiver_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;对"实现这个目标的方法?

0 个答案:

没有答案