MongoDB聚合查询索引未按预期工作

时间:2020-01-10 11:16:49

标签: mongodb indexing aggregate

我正在尝试优化仅给出两个总和和一个计数的聚合查询。我的收藏集foo的索引为:

db.foo.createIndex ( { 'info.x' : 1, 'bar.y' : 1, 'info.z' : 1 }, { background : true, name : 'foo_search_2' } );

所有这3个字段(仅这些字段)都在我的聚合查询中使用:

{ '$match' => { 'info.z' : 'Y' },
{ '$group' =>
  {
    _id : {},
    x : { '$sum' => '$info.x' },
    y : { '$sum' => '$bar.y' },
    count : { '$sum' =>  1 },
  },
},

具有使用foo_search_2的提示-它使用索引,但仍会检查每个文档!

[conn15381] command mydb.foo command: aggregate { aggregate: "foo", pipeline: [ { $match: { info.z: "Y" } }, { $group: { count: { $sum: 1 }, _id: {}, x: { $sum: "$info.x" }, y: { $sum: "$bar.y" } } } ], cursor: {}, hint: "foo_search_2", $readPreference: { mode: "secondaryPreferred" }, $db: "foo" } planSummary: IXSCAN { info.x: 1, bar.y: 1, info.z: 1 } keysExamined:79024 docsExamined:79024 cursorExhausted:1 numYields:761 nreturned:1 reslen:185 locks:{ Global: { acquireCount: { r: 1536 } }, Database: { acquireCount: { r: 768 } }, Collection: { acquireCount: { r: 768 } } } protocol:op_query 14147ms

没有提示,它不使用索引,不会检查所有文档,实际上速度更快:

[conn15382] command mydb.foo command: aggregate { aggregate: "unit", pipeline: [ { $match: { info.z : "Y" } }, { $group: { _id: {}, count: { $sum: 1 }, x : { $sum: "$info.x" }, y: { $sum: "$bar.y" } } } ], cursor: {}, allowDiskUse: true, $readPreference: { mode: "secondaryPreferred" }, $db: "arrakis" } planSummary: COLLSCAN keysExamined:0 docsExamined:79024 cursorExhausted:1 numYields:720 nreturned:1 reslen:185 locks:{ Global: { acquireCount: { r: 1454 } }, Database: { acquireCount: { r: 727 } }, Collection: { acquireCount: { r: 727 } } } protocol:op_query 12526ms

我在做什么错?我希望所有要包含的值都在索引中,因此不需要检查文档。

谢谢

0 个答案:

没有答案