dqhmtpuy94946 2014-04-25 12:15
浏览 18
已采纳

Mongodb - 具有count()的唯一ID

I build a site with referral links to products and working with mongodb. We all know that the long _id field looks ugly in Urls e.g. http://website.com/p/532600d9a715ea980a00002b/u/532af835a715eae43f00002c.

I have read some posts here and googled a while and wondered why people don't generate this easy unique id:

  1. Count current documents in collection
  2. add 1 to the number
  3. append a field to document called e.g. 'unique'

So each document got a unique number starting with 1 and urls would look like this then http://website.com/p/1/u/2.

I won't delete any document.

Where is the problem with this solution?

  • 写回答

1条回答 默认 最新

  • duanbo6871 2014-04-25 12:32
    关注

    The sane variant of this approach, where you increment a counter and assign that number, is part of the official documentation.

    The problem with your approach is that counting is a relatively expensive operation. Moreover, it's not even collision safe because two threads could count simultaneously and get the same number, so the second insert will fail.

    Generally speaking, sequences create a bottleneck because you need a single point of coordination. For a write-heavy system, the number of operations is doubled (an additional $inc for every insert). To make matters worse, sequences leak a lot of information to the outside (i.e. the number of entries in the database).

    If you're running a web shop, blog, etc. you probably want your URLs to be a lot prettier, descriptive and SEO-friendly like /products/displays/27-inch/iiyama-2734FW.

    If you're building a web application where the URLs aren't visible to search engines anyway, I believe that neither /users/433 nor /users/532af835a715eae43f00002c will be a reason for your customer to choose or not choose your application. Maybe a wise customer would, but then they'd reject the former option...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化