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 1608
清歌不尽
清歌不尽 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:42

    You can construct a new ObjectId using the string. This example uses the MongoDB console:

    db.users.find({ _id: ObjectId("4cdfb11e1f3c000000007822") })
    

    I can't tell from your question which language driver you are using (if any at all), but most drivers also support this functionality.

    You should NOT convert the ObjectId in the database to a string, and then compare it to another string. If you'd do this, MongoDB cannot use the _id index and it'll have to scan all the documents, resulting in poor query performance.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 18:56

    ObjectId is a handy way of generating a unique _id, but you are free to do it yourself. For your example,

    var o = {_id: Math.random().toString(36).substring(10)};
    collection.insert(o, handleCollision);
    

    works fine, though you have to handle collisions yourself. Then you can use direct string comparisons as needed.

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