📌  相关文章
📜  Query.prototype.explain() 如何在Mongoose中工作?(1)

📅  最后修改于: 2023-12-03 14:46:51.086000             🧑  作者: Mango

使用 Query.prototype.explain() 方法在 Mongoose 中进行查询解释

在 Mongoose 中,Query.prototype.explain() 方法可以用来返回查询的执行计划和统计信息。这个方法可以帮助我们了解查询的性能和效率,以便可以进行优化和改进。

使用方式

在查询对象上使用 explain 方法,参数是一个回调函数。回调函数的两个参数分别为(err, result):

const query = MyModel.find({ name: 'test' });
query.explain((err, result) => {
  console.log(result);
});
explain 结果

explain 返回一个包含了 MongoDB 查询执行计划和统计信息的文档。其中一些最常见的字段如下:

  • executionStats:执行统计信息
  • nReturned:返回文档的数量
  • totalKeysExamined:索引扫描的总键数
  • totalDocsExamined:文档扫描的总数

下面是一个 explain 文档的例子:

{
  "queryPlanner":{
    "plannerVersion":1,
    "namespace":"test.users",
    "indexFilterSet":false,
    "parsedQuery":{"name":{"$eq":"test"}},
    "winningPlan":{
      "stage":"FETCH",
      "inputStage":{
        "stage":"IXSCAN",
        "keyPattern":{"name":1},
        "indexName":"name_1",
        "isMultiKey":false,
        "multiKeyPaths":{"name":[]},
        "isUnique":true,
        "isSparse":false,
        "isPartial":false,
        "indexVersion":2,
        "direction":"forward",
        "indexBounds":{"name":["[\"test\",\"test\"]"]}}},
    "rejectedPlans":[]},
  "executionStats":{
    "executionSuccess":true,
    "nReturned":4,
    "executionTimeMillis":1,
    "totalKeysExamined":4,
    "totalDocsExamined":4,
    "executionStages":{
      "stage":"FETCH",
      "nReturned":4,
      "executionTimeMillisEstimate":0,
      "works":5,
      "advanced":4,
      "needTime":0,
      "needYield":0,
      "saveState":0,
      "restoreState":0,
      "isEOF":1,
      "docsExamined":4,
      "alreadyHasObj":0,
      "inputStage":{
        "stage":"IXSCAN",
        "nReturned":4,
        "executionTimeMillisEstimate":0,
        "works":5,
        "advanced":4,
        "needTime":0,
        "needYield":0,
        "saveState":0,
        "restoreState":0,
        "isEOF":1,
        "keyPattern":{"name":1},
        "indexName":"name_1",
        "isMultiKey":false,
        "multiKeyPaths":{"name":[]},
        "isUnique":true,
        "isSparse":false,
        "isPartial":false,
        "indexVersion":2,
        "direction":"forward",
        "indexBounds":{"name":["[\"test\",\"test\"]"]},
        "keysExamined":4,
        "dupsTested":0,
        "dupsDropped":0,
        "seenInvalidated":0}}}},
  "serverInfo":{
    "host":"localhost",
    "port":27017,
    "version":"4.4.1",
    "gitVersion":"ad91a93a5a31e175f5cbf8c69561e788bbc55ce1"},
  "ok":1}

其中,winningPlan 是实际执行的计划。executionStats 提供了有关执行的统计信息。在解释文档中,你可以看到查询使用了哪个索引、此查询返回的文档数量,以及查询用了多少秒。

了解查询的执行计划和统计信息对于优化和扩展应用程序非常有用。Mongoose 与 MongoDB 的协作使查询更加简单,而 explain 方法让我们更了解查询处理式的执行和统计数据。