如何正确创建索引mongodb?

Far*_*ter 3 mongodb mongodb-query mongodb-indexes

让我说我有这么大的文件.

其中2个得到了这个对象数组;

{
  status: "A",
  group: "public",
  "created.dt": ....
}

{
  status: "A",
  group: "private",
  "created.dt": ....
}
Run Code Online (Sandbox Code Playgroud)

我索引并确保这样:

db.collection.ensureIndex({"created.dt":-1});

db.collection.ensureIndex({"created.dt":-1, "status":1});
db.collection.ensureIndex({"created.dt":-1, "group":1});

db.collection.ensureIndex({"created.dt":-1, "status":1, "group":1});
Run Code Online (Sandbox Code Playgroud)

查询:

db.collection.find(
{
  "status": { 
    $in: ["A", "I"] 
  },
  "asset_group": "public"
},
{
  sort: {
   'created.dt':1
  }
}
).count();
Run Code Online (Sandbox Code Playgroud)

这是错的吗 ?

在我使这个指数仍然缓慢之后.请帮我正确索引.谢谢

ser*_*iuz 6

对于以下查询:

db.collection.find(
{
  "status": { 
    $in: ["A", "I"] 
  },
  "asset_group": "public"
},
{
  sort: {
   'created.dt':1
  }
}
).count();
Run Code Online (Sandbox Code Playgroud)

最好的指数是这样的:

db.collection.ensureIndex({"status":1, "asset_group":1, "created.dt":1});
Run Code Online (Sandbox Code Playgroud)

要么

db.collection.ensureIndex({"asset_group":1, "status":1, "created.dt":-1});
Run Code Online (Sandbox Code Playgroud)

既然你在查询

status,asset_group - 这些值可以在索引前缀中切换

并对created.dt字段进行排序- 因此created.atshuold是索引前缀中的最后一个值.注意:在排序时,索引可以遍历相反的顺序.

对于其他查询,其他索引可能更合适.了解更多关于复合索引.