Search code examples
mongodbmongodb-queryprojection

Projection in MongoDb


I am learning MongoDb and a question came to my mind regarding projection.

When we do a projection for some fields, what does MongoDB do? Would it read the whole document and then drop some fields and returns the results or it won't read excluded fields and return the fields mentioned in the query.

For e.g. If I have a document with 4 fields and 3 arrays(each of size ~10) and I just want the 4 fields and not the arrays. Would MongoDB read the whole document and drop the array or would just read the 4 fields?

If it's the first case how the execution time or latency would differ if the array becomes big in the document?


Solution

  • The document is compressed on storage , so mongo need to read the document first , uncompress it and get the fields specified in the filter only. The trick here is that when you search by some of the fields you need to index them so the search to happen faster in memory and to avoid mongo to read all documents one by one and check for the searched field. And if you need faster access for only those fields it is best all those fields to be in compound index and you search them via so called "covered query" , then you will search only in memory and fetch only from memory without accessing storage which will be much more faster. Also in many cases it happen that same documents are searched multiple times so the mongoDB predictive algorithm is caching those documents in memory to be accessed faster.