One-to-One Relationship

I have a question about “One-to-One Relationship” lesson.

In lesson and lab there are no info about why or why not
establishing connection beetwen collections using _id fields.

For me it seems very natural to use them. They always exists,
always have index, always unique and always type compatible*.

In case of joining big collections we dont need to create additional
indexes.

What are pros and cons?

In my view, there are few reasons:

  1. They are less human-readable
  2. They occupy more space, i.e. a 12-byte ObjectID across two collections
  3. I would imagine that a 4 or 8-byte Integer field would perform better than a 12-byte field when it comes to indexed search
  4. I don’t know the effects of sharding the collection because the _id field contains a timestamp

I think at the end of the day it boils down to the implementation. Some use cases would prefer the _id being used and in some cases you may need to maintain your own id. The requirements will dictate the solution.

I’m sure that @danielcoupal has a better view on this.

1 Like

Don’t forget, you can set the value of _id yourself when creating a document, and it doesn’t necessarily need to be an ObjectID, it could be some value which has a business meaning to your application, in which case it would be a great candidate to use for joining two collections with a 1-1 relationship.

2 Likes

I agree with @Simon_39939 completely.

… and bear in mind that the _id field is immutable, i.e. the value cannot be changed/updated. Meaning, once you’ve set the value, it becomes permanent.

2 Likes

… and it must be unique within a given collection.

2 Likes