Is it ok to use Mongo's “Object ID” as its unique identifier? If so, how can I convert it to a string and look it up by string?

前端 未结 3 1632
清歌不尽
清歌不尽 2021-01-07 18:30

For example...

user/view/?id=324gijsdfi3h25o1

I can str() it...but...

How can I find it up by string?

3条回答
  •  没有蜡笔的小新
    2021-01-07 18:50

    To your questions:

    Is it ok to use Mongo's “Object ID” as its unique identifier?

    Yes, it is intended for this purpose. Making unique IDs can be a pain in sharded environments, so MongoDB does this for you.

    If so, how can I convert it to a string and look it up by string?

    Don't. It's not a string. MongoDB actually lets you override the default ID. So if you start searching for #"4cdfb11e1f3c000000007822", Mongo thinks that you're looking for a string. If instead you look for ObjectId("4cdfb11e1f3c000000007822"), Mongo will look for the ObjectId (or MongoID).

    In your question, it looks like you're trying to pass it in as a string. How you convert this to an "objectid" will depend on your driver. PHP has a MongoId. Other drivers have a similar function.

提交回复
热议问题