Generation of _id vs. ObjectId autogeneration in MongoDB

后端 未结 1 577
一生所求
一生所求 2021-01-14 03:52

I\'m developing an application that create permalinks. I\'m not sure how save the documents in MondoDB. Two strategies:

  1. ObjectId autogeneration

    Mong

相关标签:
1条回答
  • 2021-01-14 04:19

    ObjectIds are there for situations where you don't have a unique key for every document in a collection. They're unique, so you don't have to worry about conflicts and they shard reasonably well in large deployments without too much worry (they have they're pros and cons, read more here).

    The ObjectId also contains the timestamp of the client where the ObjectId was generated (unless the DB server is configured to generate all keys). With that, as you noticed, you can use the time stamp to perform some date operations. However, if you plan on using the Aggregation Framework, you'll find that you can't use an ObjectId in any date operations currently (issue). If you want to use the AF, you'll need a second field that contains the date, unfortunately doubly storing it with the ObjectId's internal value.

    If you can be assured that the _id you're generating is unique, then there's not much reason to use an ObjectId in your data structure.

    0 讨论(0)
提交回复
热议问题