首页 > 解决方案 > 如何在 MongoDB 中正确创建索引以搜索整个集合?

问题描述

我有一个名为的集合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

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

标签: javascriptnode.jsregexmongodbmongodb-query

解决方案


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

以下是创建索引的方法:

db.collectionName.createIndex(key_name)

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


推荐阅读