Is query speed faster if I query for non-nested fields?

Given the following schema

{
_id: 'abb',
projectId:"1"
project:{
name:'abc',
id:'1'
}
}

A senior dev told me that if I query for projectId it would be a faster query compared to
if I query for “project.id”.
Is this true?
I just wanted some confirmation and explanation as to why this is

Well, you should definitively invite your

here in order for him/her to supply the reasoning behind his/her remark. There are factors more important than that for performance. A indexed project.id will be a lot faster compared to a non-indexed projectId.

Functionally, I prefer to have a project: object.

  1. I can $project the whole project: object to get all and only the project attributes. Otherwise you have to project each and every project attributes if everything is at the top level. Adding a project attribute will need a code update to get the new attribute at the top level. There is nothing to do when it is nested.
  2. In your code you may pass the project: object to a function knowing that the function won’t be able to access or modify the other top level attributes.
  3. You do not have to do name mangling when the same attribute name would apply. Something like:
{
   user : { id : 1 , name : steevej }
   project : { id : 2 , name : data-warehouse }
}

vs

{
   userId : 1 ,
   userName : steevej , 
   projectId : 2 ,
   projectName : data-warehouse
}
  1. It is easier to expand the model from a single user/project to multiple user/project.
{
   user : { id : 1 , name : steevej }
   projects :
   [
     { id : 2 , name : data-warehouse } ,
     { id : 3 , name : web-interface } ,
   ]
}

vs

{
   userId : 1 ,
   userName : steevej , 
   projectId_0 : 2 ,
   projectName_0 : data-warehouse ,
   projectId_1 : 3 ,
   projectName_1 : web-interface
}

Then each element of projects: could be processed by the same project functions directly. Otherwise you have un-mangle the name before calling the functions.

So please ask your senior dev to provide his/her input.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.