Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Indexing and Projection

I have a few questions about MongoDB:

(1) Does indexing help with projection?

(2) I have assigned a collection a number of indexes and tried to run a find with sort, and then use explain, it shows BtreeCursor index on the sorted field.

Could it be that the other indexes have helped in the query part and explain just didn't show it because it shows only the last index that helped the find?

Or explain should show all indexes that assisted in querying, sorting, etc?

Thanks.

like image 311
oikonomiyaki Avatar asked Dec 04 '14 05:12

oikonomiyaki


People also ask

What is a MongoDB projection?

In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

What does indexing do in MongoDB?

The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.

Are MongoDB indexes strongly consistent?

Learn more about MongoDB transactions here. Supported indexing strategies such as compound, unique, array, partial, TTL, geospatial, sparse, hash, wildcard and text ensure optimal performance for multiple query patterns, data types, and application requirements. Indexes are strongly consistent with the underlying data.


1 Answers

Does indexing helps in projection?

I believe the only time it will really help (defined by performance etc) is if the query is "covered": http://docs.mongodb.org/manual/tutorial/create-indexes-to-support-queries/

So for example, if you wanted to query on {d:1, e:2} and get back {_id, t, e}, you would do:

db.t.ensureIndex({d:1 , e:1, _id:1, t:1});
db.t.find({d:1, e:2}, {_id:1, t:1, e:1});

And that query's explain() output would show indexOnly as true meaning that it never loaded documents from disk to return a response.

So yes, indexes can help with projection under certain circumstances.

I have assigned a collection a number of indexes and tried to run a find with sort, and then use explain, it shows BtreeCursor index on the sorted field.

Yes it does.

Could it be that the other indexes have helped in the query part and explain just didn't show it because it shows only the last index that helped the find?

If you are a victim of index intersectioning then you would use an explain(true) to show all index plans that were used.

It is good to note that separate indexes are not used for find and sort with intersectioning, so the answer here is actually no: http://docs.mongodb.org/manual/core/index-intersection/#index-intersection-and-sort

like image 51
Sammaye Avatar answered Oct 09 '22 06:10

Sammaye