我有一个名为“对话”的模型,还有一个名为“消息”的模型,现在我想检索所有带有最后一个消息的对话(每个对话仅1条消息),因此我过滤了对话ID并查询了消息,但是在每次对话中我都无法获取此消息(最后消息)。
let conversations = await ConversationModel.find({});
const conversationIds = conversations.map(conversation => conversation._id)
// ConversationIds is basically ["conversation1", "conversation2", "conversation3"]
// Te problem is here, i want to attach the las message for each conversation, if i put limit(1)
// i will get 1 record for all query, but i want the last message record for each conversation.
MessageModel.find({ _id: { "$in" : conversationIds} }, ...);
答案 0 :(得分:0)
根据评论中收集的信息;在MessageModel
个文档包含用于标识最新文档的时间戳的情况下,可以实现此目的。
想法:通过$match
过滤基于conversationIds
的消息,并按timestamp
进行下一阶段的过滤,其中对话参考上的$group
(让我们说conversation_id
),然后由$first
累加器选择最新的。
汇总查询: playground link
db.collection.aggregate([
{
$match: {
conversation_id: {
$in: conversationIds
}
}
},
{
$sort: {
timestamp: -1
}
},
{
$group: {
_id: "$conversation_id",
latest_doc: {
$first: "$$ROOT"
}
}
}
]);