【问题标题】:How to create index properly in MongoDB to search in entire one collection?如何在 MongoDB 中正确创建索引以搜索整个集合?
【发布时间】:2021-02-19 19:06:06
【问题描述】:

我有一个名为 people 的集合,这个集合几乎有 100k documents..

虽然我是前端开发人员,但我不知道如何提高搜索性能。

我搜索如下:

const phoneNumbers = [
   { "phone": { "$regex": `1` } },
   { "phone": { "$regex": `2` } },
   { "phone": { "$regex": `3` } },
   { "phone": { "$regex": `4` } },
   { "phone": { "$regex": `5` } },
   { "phone": { "$regex": `xxx` } },
   { "phone": { "$regex": `999` } },
   { "phone": { "$regex": `1000` } },
];


peopleCollection.find({$or: phoneNumbers}).toArray((error, matchedDocs)=> {
   // returning matched docs
});

您可以看到我的搜索结构,您对创建 index 有什么建议?

这对创建 index 有帮助吗? 如果是,我如何创建正确的 index

【问题讨论】:

标签: javascript node.js regex mongodb mongodb-query


【解决方案1】:

索引不会降低搜索表达式的复杂性,而是帮助数据库更快地找到匹配的结果(即降低时间复杂度)。

创建索引的方法如下:

db.collectionName.createIndex(key_name)

上面的单行操作在 key_name 键上创建索引。

【讨论】:

  • 请告诉我如何创建它,因为您可以看到我的代码
猜你喜欢
  • 1970-01-01
  • 2017-05-24
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多