mccormjt
mccormjt

Reputation: 23

Meteor indexing for efficient sorting

I want to sort a collection of documents on the backend with Meteor in a publication. I want to make sure I index the collection properly and I couldnt find any concrete ways to do this for the fields I want.

Basically I want to find all the documents in collection "S" that have field "a" equal to a specific string value. Then after I have all those documents, I want to sort them by three fields: b, c (descending), and d.

Would this be the right way to index it:

S._ensureIndex({ a: 1 });
S._ensureIndex({ b: 1, c: -1, d: 1 });

S.find({ a: "specificString"}, { sort: { b: 1, c: -1, d: 1 } });

As a bonus question, field "d" is the time added in milliseconds and it would be highly unlikely that there is a duplicate document with all 3 fields being the same. Should I also include the unique option as well in the index?

S._ensureIndex({ b: 1, c: -1, d: 1 }, { unique: true });

Will adding the unique option help any with sorting and indexing performance? I was also wondering what the general performance was for an indexed sort by mongo? On their page it says indexed sorts dont need to be done in memory because it is just doing a read. Does this mean the sort is instant?

Thanks for all your help :)

Upvotes: 0

Views: 193

Answers (1)

mccormjt
mccormjt

Reputation: 23

I was able to find my own answer here: http://docs.mongodb.org/manual/tutorial/sort-results-with-indexes/#sort-and-non-prefix-subset-of-an-index

Basically the correct way to index for my example here is:

S._ensureIndex({ a: 1, b: 1, c: -1, d: 1 });

S.find({ a: "specificString"}, { sort: { b: 1, c: -1, d: 1 } });

-- As for my other subquestions.

  1. Because you are using the index here, the performance is instant. However do keep mind that having a 4 field index can be very expensive in other ways.

  2. Without looking this up for sure....my hunch is that including the "unique: true" would not make a difference in performance since it is already instant.

Upvotes: 1

Related Questions