Using UUIDs instead of ObjectIDs in MongoDB

后端 未结 5 469
误落风尘
误落风尘 2021-01-30 03:32

We are migrating a database from MySQL to MongoDB for performance reasons and considering what to use for IDs of the MongoDB documents. We are debating between using ObjectIDs,

5条回答
  •  执念已碎
    2021-01-30 04:26

    The _id field of MongoDB can have any value you want as long as you can guarantee that it is unique for the collection. When your data already has a natural key, there is no reason not to use this in place of the auto-generated ObjectIDs.

    ObjectIDs are provided as a reasonable default solution to safe time generating an own unique key (and to discourage beginners from trying to copy SQL's AUTO INCREMENT which is a bad idea in a distributed database).

    By not using ObjectIDs you also miss out on another convenience feature: An ObjectID also includes an unix timestamp when it was generated, and many drivers provide a funtion to extract it and convert it to a date. This can sometimes make a separate create-date field redundant.

    But when neither is a concern for you, you are free to use your UUIDs as _id field.

提交回复
热议问题