mongoDB 実行計画を取得する

mongoDB 実行計画を取得する

mongoDBで、実行計画を取得する手順を記述してます。「mongoDB」の通常のリレーショナルDBように実行計画を取得することが可能です。「explain」を使用します。

環境

  • OS CentOS Stream release 9
  • MongoDB 6.0.2

手順

実行計画を取得するには、「db.コレクション名.find().explain()」を使用します。

db.コレクション名.find().explain()

実際に、以下のデータベース「hoge」にある「foo」というコレクション(テーブル)のドキュメント(レコード)を使用して、findを実行して実行計画を表示してみます。

> use hoge

> db.foo.find()

[
  {
    _id: ObjectId("6364ae7f06a29c57f191d1b7"),
    name: 'itiro',
    age: 10,
    gender: 'm'
  },
  {
    _id: ObjectId("6364ae7f06a29c57f191d1b8"),
    name: 'jiro',
    age: 20,
    gender: 'm'
  },
  {
    _id: ObjectId("6364ae7f06a29c57f191d1b9"),
    name: 'saburo',
    age: 30,
    gender: 'm'
  },
  {
    _id: ObjectId("6364ae7f06a29c57f191d1ba"),
    name: 'jiro',
    age: 25,
    gender: 'f'
  },
  {
    _id: ObjectId("6364ae7f06a29c57f191d1bb"),
    name: 'jiro',
    age: 30,
    gender: 'x'
  }
]

実行計画を表示してみます。

> db.foo.find({name:'jiro'}).explain()

{
  explainVersion: '1',
  queryPlanner: {
    namespace: 'test.foo',
    indexFilterSet: false,
    parsedQuery: { name: { '$eq': 'jiro' } },
    queryHash: '64908032',
    planCacheKey: '64908032',
    maxIndexedOrSolutionsReached: false,
    maxIndexedAndSolutionsReached: false,
    maxScansToExplodeReached: false,
    winningPlan: {
      stage: 'COLLSCAN',
      filter: { name: { '$eq': 'jiro' } },
      direction: 'forward'
    },
    rejectedPlans: []
  },
  command: { find: 'foo', filter: { name: 'jiro' }, '$db': 'test' },
  serverInfo: {
    host: 'localhost.localdomain',
    port: 27017,
    version: '6.0.2',
    gitVersion: '94fb7dfc8b974f1f5343e7ea394d0d9deedba50e'
  },
  serverParameters: {
    internalQueryFacetBufferSizeBytes: 104857600,
    internalQueryFacetMaxOutputDocSizeBytes: 104857600,
    internalLookupStageIntermediateDocumentMaxSizeBytes: 104857600,
    internalDocumentSourceGroupMaxMemoryBytes: 104857600,
    internalQueryMaxBlockingSortMemoryUsageBytes: 104857600,
    internalQueryProhibitBlockingMergeOnMongoS: 0,
    internalQueryMaxAddToSetBytes: 104857600,
    internalDocumentSourceSetWindowFieldsMaxMemoryBytes: 104857600
  },
  ok: 1
}

実行計画が取得されていることが、確認できます。