Search code examples
mongodbmongodb-querymongodb-indexes

Understanding mongodb indexing: Indexing linked document that is frequently queried


Here is a simple example of the kind of query my app makes

So you have a notepad and notes collection. The note documents are linked to the notepad document using the notepadId.

So a typically query looks like:

Notes.find({notepadId: notepad._id})

A user can have hundreds of notes per notepad. And they switch between notepads often. Also users collaborate on notepads.

I also have a mechanism that counts all the notes in the notepad on the server on page load. This is because I need to know how many pages to show since I use pagination.

Notes.find({notepadId: notepad._id}).count()

I am not very familiar with MongoDB indexing and have tried to search for 'Indexing linked documents' and can't find any info on indexing linked documents.

Is this a common practice to index linked document fields?

So in this case I would want to set an index on the Notes collection, on the field notepadId

Good idea, bad idea, why?


Solution

  • The documents become "linked" only on application layer. There is nothing special in notepadId field in mongodb itself. Indexing by this field will make counting extremely efficient, as it is a covered query, which requires no disk IO.