【发布时间】:2016-03-15 08:39:32
【问题描述】:
使用 Mongo 3.2。
假设我有一个具有此架构的集合:
{ _id: 1, type: a, source: x },
{ _id: 2, type: a, source: y },
{ _id: 3, type: b, source: x },
{ _id: 4, type: b, source: y }
当然,我的数据库更大,类型和来源也更多。
我已经创建了 4 个类型和来源的索引组合(即使 1 个就足够了):
{type: 1}
{source: 1},
{type: 1, source: 1},
{source: 1, type: 1}
现在,我正在运行这个独特的查询:
db.test.distinct("source", {type: "a"})
问题是这个查询需要更多的时间。 如果我用 runCommand 运行它:
db.runCommand({distinct: 'test', key: "source", query: {type: "a"}})
这是我得到的结果:
{
"waitedMS": 0,
"values": [
"x",
"y"
],
"stats": {
"n": 19400840,
"nscanned": 19400840,
"nscannedObjects": 19400840,
"timems": 14821,
"planSummary": "IXSCAN { type: 1 }"
},
"ok": 1
}
由于某种原因,mongo 在查询阶段仅使用type: 1 索引。
它也应该将索引用于不同的阶段。
这是为什么?使用{type: 1, source: 1} 索引会好很多,不是吗?现在它正在扫描所有type: a 文档,同时它有一个索引。
我做错了吗?对于这种独特的,我有更好的选择吗?
【问题讨论】:
标签: mongodb mongodb-query