Grouping fields

What is the benefit of grouping fields rather than putting them in the same level. for example: I need to reference another collection:
users = [{ _id: 1123, name: …, pics:[ { _id: 123, path: … }, …]}, …]
If I want to reference a user and a pic in his profile I would need to use both id’s like this:
posts=[{ _id: 222, users_id: 1223 users_pics_id: 123, …}, …]
Would there be any difference if I grouped users_id and users_profiles_id into a single document? like this: posts = [{ _id, user: { users_id: 1223, users_profiles_id: 123}, …}, …]
What are the considerations here?
Thank you.

Hey @log_blackhole

I do not think (could be wrong) there would be any performance difference whether you have fields all at the same level,

{
  _id: 222,
  users_id: 1223,
  users_pic_id: 123
}

or in an embedded document.

{
  _id: 222,
  user: {
    users_id: 1223,
    users_pic_id: 123
  }
}

However there are considerations when thinking about embedding a whole other document vs referencing; see the links below

Model Relationship between documents
One to One
One to Many Embedded
One to Many Reference

1 Like

@log_blackhole,

as @natac13 said, there is no performance difference.
It is more an organization choice.
Because the reference, the user, is more than one field, it would be preferred to keep those related fields organized together.

If later another field is added in the reference, it is still a clean modification in the code, just continue to read the “user” sub-document.

Regards,
MongoDB University.

1 Like