通过其他相关集合对mongo集合进行排序

时间:2017-03-21 10:39:16

标签: mongodb mongodb-query aggregation-framework

我的收藏架构如下

架构:用户

users: [
  {
    id: 1234,
    username: 'someuser'
  }
];

架构:消息

messages: [
  {
    id: 1,
    sender_id: <user_id>,
    receiver_id: <user_id>,
    text: 'some message',
    created_at: <timestamp>
  }
];

我需要所有用户列出带有时间戳的最后一条消息。应根据最后的消息对用户列表进行排序。时间戳。

我尝试了以下代码。

db.users.aggregate([
{
    $lookup: {
       from: 'messages',
       localField: '_id',
       foreignField: ['sender_id', 'receiver_id'], // user id could either be sender id or receiver id. but this field expecting string instead of an array,
       as: 'message' // I am expecting single object of message instead collection of messages,
    }
},
{
    $sort: {
        'message.created_at': -1
    }
}
])

我知道可以使用rdms轻松完成。我希望mongodb比我想的要好很多。

0 个答案:

没有答案
相关问题