Chapter 2: Relationships Many-to-Many Relationship

In the lesson Many-to-Many Relationship, I don’t understand why there are both an _id field and a storeId field in the stores collection.

Why would someone have two id fields? Does it not hurt writes and space (2 index to maintain) without any benefit?

I’m missing something here! Thanks a lot

Hi @Erwan_N_A

In some cases such as the stores example, the second field for ‘storesId’ is present because the store is actually represented by a human-readable string versus an ObjectId. This can simplify the query on the application side as the person querying is then searching a list of strings that meaningfully represent various stores/shops.

That said you could overload the ObjectID by making it either represent the StoreID but this will add a degree of complexity to your indexes and they must be managed.

In this example, creating a storeId field does not explicitly call for or create a second index. It might be useful to add depending on the most frequent queries used by the application but it may not be necessary.

In many cases, several indexes are required in a collection to ensure that the frequently requested queries can be serviced where the query shape (fields requested) differ. Questioning whether each index is required is a good practice and I think you are on the right approach to building performant MongoDB indexing strategies for your application.

Hope this helps explain it!
Eoin

1 Like

Thanks a lot for your detailed answer.

If we just put the storeId in the _id field, how would it add more complexity?

We would have only the _id field with integers (store Id)

It’s just that part that I don’t understand yet.

might be referring to the fact that the default IDs ( _id )are by default indexed. These indexes are created when a collection is created. Another consideration may be the default Ids are not strings they are internal Object references, for faster lookup, replacing with a regular string might be slower performance, Also may be in sharded environments the making a unique ID by application might be bit more work for application, mongoDB does this for application with the default ID.