Search code examples
sortingmongodbparent

mongo db sorting on both parent and child collection fields


Ok I have two Collections, Parent and Child. A parent collection can have multiple Child documents.

Now I'd like to be able to to sort ChildCollection documents by it's own fields as well as the fields of it's parent. Is this possible? Yes, I could put it in one big Collection but it will be a lot of redundancies. This would be for millions of records so the more that can be done on the server the better.

ParentCollection
_id : "parentid1"
field1 : "val1"
field2 : "val2"
fieldx.......

ChildCollection
_id : "childid1"
_parentid: "parentid1"
field1 : "val3"
field2 : "val4"
fieldx.........

Solution

  • To sort child collection on parent collection fields you should put parent fields on which you want sort into the each child. There is no another way to do this. And you will need update these fields in all child's when you update parent document. Mongodb love denormalization, so don't care to this. Also to increase speed of parent fields update you can make child updates async.