我正在尝试为消息传递系统数据导出编写一个聚合管道,它涉及一些查找管道嵌套。我目前正在经历与我期望的表现相矛盾的表演。以下查询似乎需要很长时间才能运行(即使它确实完成了):
conversations.aggregate([
{
"$match": {
...
}
},
{
"$lookup": {
"from": "messages",
"let": {"convo_id": "$_id"},
"pipeline": [
{
"$match": {
"$expr": {
"$eq": ["$conversation_id", "$$convo_id"]
}
}
},
{
"$sort": {
"created": 1
}
},
{
"$lookup": {
"from": "users",
"localField": "user_id",
"foreignField": "_id",
"as": "user"
}
},
{
"$unwind": {
"path": "$user",
"preserveNullAndEmptyArrays": true
}
}
],
"as": "messages"
}
},
{
"$project": {
...
}
}
])
但是,如果我移动$sort
阶段,以便在$lookup
和/或$unwind
阶段之前,查询将立即运行。我还检查了输出结果,这似乎都是正确的(这使我相信它实际上是在处理排序阶段,而不仅仅是忽略它)。
这与我预期的行为相矛盾。我希望在$sort
之后,$match
和$lookup
之前进入$unwind
阶段会更快,但是似乎相反。我想知道是否有人对此有何见解。