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 1642
清歌不尽
清歌不尽 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.

提交回复
热议问题