如何正确创建索引 mongodb?

how to create index mongodb properly?

假设我有这么大的文件。

他们中有 2 人得到了这个对象数组;

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

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

我索引并确保这样:

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});

查询:

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

错了吗?

在我使这个索引仍然很慢之后。 请帮我正确index.thank你

对于以下查询:

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

最好的索引是:

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

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

由于您在

上查询

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

中切换

并在 created.dt 字段上排序 - 因此 created.at 应该是索引前缀中的最后一个值。注意:排序时索引可以逆序遍历。

对于其他查询,其他索引可能更合适。 详细了解 compound indexes