Pre created _id field ObjectId versus insertion time _id field ObjectId

Hi everyone, we know it is possible to create the ObjectId before insertion, which is great for validation purposes.

My questions are:

  1. Is there any drawback in doing so?
  2. When we don’t, is the driver creating the ObjectId beforehand anyway, and we just feels it is created on DB Server?
  3. If it is created on DB Server, does it has any advantage, regarding collision, for example?

Cheers,

Hello @Adriano_Tirloni,

I am guessing that you are talking about the required field _id, and its type ObjectId,

if you don’t specify the _id field ObjectID then most of the MongoDB driver (client-side) will include the _id field and generate the ObjectId and pass it to the insert object. If the client is customized or doesn’t send _id in some cases, the MongoDB server (mongod) will add the _id field and generate ObjectID.

If you are worried about ObjectId uniqueness then in both cases ObjectId will be unique because of its structure.

Client Side: The risk of collisions with client-side generation is negligibly small in most scenarios.

Server Side: Will do extra operation on the server side if _id is not present in the insert document, also it will take the extra load if you do the bulk operation.

A preferable approach is to generate _id from the client-side, but it depends on your use case and requirement.

Well this is great, because there is the mental model from SQL that “My Id can only be obtained at insertion time”, and the definitive id clientside will make it is easier to deal with validations and associations.

Thank you,

1 Like

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