【问题标题】:how to create index mongodb properly?如何正确创建索引 mongodb?
【发布时间】:2017-04-13 01:21:21
【问题描述】:

假设我有这么大的文件。

其中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();

错了吗?

在我使这个索引仍然很慢之后。 请帮我正确索引。谢谢

【问题讨论】:

  • 没有看到您的查询就无法判断(例如:查找、排序等)
  • @FirdausRamlan 好吧,我已经编辑了那个帖子。

标签: mongodb mongodb-query mongodb-indexes


【解决方案1】:

对于以下查询:

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 的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 2021-02-19
    • 1970-01-01
    • 2011-08-20
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多