我有一个Chat MongoDB数据库,其中包含以下集合:
chats: {
chat_id: string, // indexed 1, unique
last_updated: number, // indexed -1
// other data...
}
messages: {
chat_id: string; // indexed 1
message_id: string; // indexed 1, unique
timestamp: number; // indexed -1
// other data...
}
我希望能够查询最近的10次聊天,并接收聊天文档和与该聊天相关联的最新消息.目前,我正在做的是:
// step 1: find the 10 most recent chats
const chats = await db.collection('chats')
.find()
.sort({last_updated: -1})
.limit(10)
.toArray();
// step 2: use $group to find the most recent message in each chat
const messages = await db.collection('messages').aggregate([
{ $match: { chat_id: { $in: chats.map(chat => chat.chat_id) } } },
{ $sort: { timestamp: -1 } },
{ $group: { _id: '$chat_id', latest_message: { $first: '$$ROOT' } } }
]).toArray();
我担心,如果聊天中有大量与之相关的消息,$Sort和$Group阶段将变得很慢.有没有更好的方法来做到这一点,或者我是不是过早地试图优化一些运行良好的东西?