J-Rou
J-Rou

Reputation: 2286

Multiple indexes with different definitions in mongodb

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.

Upvotes: 0

Views: 2999

Answers (1)

Pavel Veller
Pavel Veller

Reputation: 6115

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.

Upvotes: 3

Related Questions