简体   繁体   中英

Mongodb taking too much time to find the record

I have mongodb on localhost, in database I have 90 million records. When I search for any record via db.emails.find({"name":"example"}) , it is taking too long to get result. Is there any way I can increase speed of mongodb?

Create index for name field

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. This index on other hand stores only ordered values of name field which can be checked quickly.

There is limit for index key. Totals size of index entry must be less than 1024 bytes. 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.

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. For example if you want everyone that has gmail accounts, you could perform a search like

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

I believe this would speedup your code a lot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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