0

The question is a very simple one, can you have more than one index in a collection. I suppose you can, but every time I search for multiple indexes I get explanations on compound indexes and that is not what I'm looking for.

All I want to do is make sure that I can have two simple separate indexes. (I'm using PHP, I'll use php code formatting, but I understand

db.posts.ensureIndex({ my_id1: 1 }, {unique: true, background: true});
db.posts.ensureIndex({ my_id2: 1 }, {background: true});

I'll only search for one index at a time.

Compound indexes are not what I'm looking for because:

  1. one index is unique and the other is not.

  2. I think it's not going to be the fastest option. (open the link to understand the reason I think its going to be slower. link)

I just want to make sure that the indexes will work.

1 Answer 1

3

You sure can have indexes defined the way you have it. From MongoDB documentation:

How many indexes? Indexes make retrieval by a key, including ordered sequential retrieval, very fast. Updates by key are faster too as MongoDB can find the document to update very quickly. However, keep in mind that each index created adds a certain amount of overhead for inserts and deletes. In addition to writing data to the base collection, keys must then be added to the B-Tree indexes. Thus, indexes are best for collections where the number of reads is much greater than the number of writes. For collections which are write-intensive, indexes, in some cases, may be counterproductive. Most collections are read-intensive, so indexes are a good thing in most situations.

I also recommend you look at how Mongo will decide what index to use when it comes to running a query that goes by both fields.

Also take a look at their Indexing Advice and FAQ page. It will explain things like only one index per query, selectivity, etc.

p.s. This slideshare deck from 10gen suggests there's a limit of 40 indexes per collection.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. In the examples I never saw two indexes, one after the other. (In the same script) . I just wanted to make sure. Thank you also for the extra info, it will become very useful.
Thanks for the information of MongoDB can have 40 indexes per collection it may have changed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.