在 mongo db 上索引聚合慢查询

时间:2021-02-21 06:45:40

标签: mongodb

我在 mongo 上遇到了一个关于集合中大约 50k 个文档的缓慢查询

如何索引它?

我尝试添加以下索引,但没有解决问题

db.getCollection("events").createIndex({ "area.area_id": 1, "execute_time": -1 })
"Slow query","attr":{"type":"command","ns":"events.events",
"command":{"aggregate":"events","pipeline":
[
  {"$facet":{"1":[{"$match":{"area.area_id":"1"}},
  {"$sort":{"execute_time":-1}},{"$limit":30}
],


"2":

[
  {"$match":{"area.area_id":"2"}},
  {"$sort":{"execute_time":-1}},{"$limit":30}]}}
]
,"cursor":{},
"lsid":
{"id":{"$uuid":"2be3c461-dfc7-4591-adaf-da9454b9615c"}},"$db":"events"},
"planSummary":"COLLSCAN","keysExamined":0,"docsExamined":37973,"cursorExhausted":true,"numYields":37,"nreturned":1,
"reslen":118011,"locks":{"ReplicationStateTransition":{"acquireCount":{"w":61}},"Global":{"acquireCount":{"r":61}},
"Database":{"acquireCount":{"r":61}},"Collection":{"acquireCount":{"r":61}},"Mutex":{"acquireCount":{"r":24}}},"storage":{},"protocol":"op_msg","durationMillis":262}}

我的查询:


 this.collection.aggregate([
                {$facet: facetObj }])

每个方面 obj 类似于:

    facet[x] = [
                {$match: {'area.area_id': x}},         
                {$sort: { execution_time: -1 }},
                {$limit: limit}
            ]

2 个答案:

答案 0 :(得分:3)

您不能在 $facet 阶段使用索引。

From the MongoDB documentation

<块引用>

$facet 阶段及其子管道不能使用索引,即使其子管道使用 $match 或者 $facet 是管道中的第一个阶段。 $facet 阶段在执行期间将始终执行 COLLSCAN。

答案 1 :(得分:0)

您没有显示任何输入数据或预期结果。但是,据我所知,一种方法可能是这样的:

db.collection.aggregate([
  { $match: { area_id: { $in: [ 1, 2 ] } } },
  { $sort: { execute_time: -1 } },
  {
    $group: {
      _id: "$area_id",
      execute_time: { $push: "$execute_time" }
    }
  },
  {
    $set: {
      execute_time: { $slice: [ "$execute_time", 30 ] }
    }
  }
])

Mongo playground