简体   繁体   English

Mongodb花费太多时间查找记录

[英]Mongodb taking too much time to find the record

I have mongodb on localhost, in database I have 90 million records. 我在本地主机上有mongodb,在数据库中我有9000万条记录。 When I search for any record via db.emails.find({"name":"example"}) , it is taking too long to get result. 当我通过db.emails.find({"name":"example"})搜索任何记录时,获取结果的时间太长。 Is there any way I can increase speed of mongodb? 有什么办法可以提高mongodb的速度吗?

Create index for name field name字段创建索引

db.emails.createIndex( { name: 1} )

If you don't have index for field, then mongodb must perform a collection scan when executing query, ie scan every document in collection to check value of name field that match your query. 如果您没有字段索引,则mongodb必须在执行查询时执行集合扫描 ,即扫描集合中的每个文档以检查与查询匹配的name字段的值。 This index on other hand stores only ordered values of name field which can be checked quickly. 另一方面,该索引仅存储可以快速检查的name字段的有序值。

There is limit for index key. 索引键有限制。 Totals size of index entry must be less than 1024 bytes. 索引条目的总大小必须小于1024个字节。 But you can use text index if you want to search queries on string content: 但是,如果要搜索有关字符串内容的查询,可以使用文本索引:

db.emails.createIndex( { name: "text"} )

Also if you want to search for exact match, then you can use hashed index: 另外,如果要搜索完全匹配,则可以使用哈希索引:

db.emails.createIndex( { name: "hashed" })

Usually to speedup mongodb queries, what one can do is to prepare a composed index. 通常,为了加速mongodb查询,可以做的是准备一个组合索引。

In your case, since it is email addresses, what I would suggest you to do is to put the mail as the id and perform search using regular expressions that are case insensitive. 在您的情况下,由于它是电子邮件地址,因此我建议您将邮件作为id并使用不区分大小写的正则表达式执行搜索。 For example if you want everyone that has gmail accounts, you could perform a search like 例如,如果您希望所有人都拥有gmail帐户,则可以执行如下搜索

db.users.find({_id:/@gmail.com/})

I believe this would speedup your code a lot 我相信这将大大加快您的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM