【发布时间】:2019-12-16 08:07:01
【问题描述】:
尝试在 Mongo 上运行聚合函数的查询,当我希望的结果不到一秒时,该查询当前需要 16 秒
{
"$lookup": {
"from": "session_attendances",
"let": { "id": "$_id" },
"pipeline": [
{
"$match": {
"$expr": {
"$eq": ["$student", "$$id"]
}
}
},
{
"$project": {
"attendance_code": "$attendance_code"
}
}
],
"as": "attendance"
}
},
{
// keep only matched students, can skip this and modifiy the next phase incase no such documents exists.
"$unwind": "$attendance"
},
{
"$lookup": {
"from": "attendance_codes",
"let": { "attendance_code": "$attendance.attendance_code" },
"pipeline": [
{
"$project": {
"type": 1
}
},
{
"$match": {
"$expr": {
"$eq": ["$_id", "$$attendance_code"]
}
}
}
],
"as": "attendance_code"
}
},
{
//again assuming we want to keep matched docs otherwise why lookup?
"$unwind": "$attendance_code"
},
{
"$group": {
"_id": { "a": "$attendance.attendance_code", "id": "$_id" },
"total": { "$sum": 1 },
"data": { "$first": "$$ROOT" } // if u want to keep document data
}
}
希望有人可以回答我的代码的哪一部分导致运行时间如此缓慢。
【问题讨论】:
-
您可能会在以下帖子中找到答案:stackoverflow.com/questions/43742635/…
标签: mongodb aggregate-functions