Reputation: 271764
For example...
user/view/?id=324gijsdfi3h25o1
I can str()
it...but...
How can I find
it up by string?
Edit: I want each document in Mongo to have a unique identifier (usually a string) that I can look up on. I was hoping the Object ID could be this (since it has a lot of letter and it's unique.) And I want it to work with HTTP GET. view?uid=e93jfsb0e3jflskdjf
Upvotes: 25
Views: 19478
Reputation: 10892
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.
Upvotes: 0
Reputation: 45287
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.
Upvotes: 17
Reputation: 32184
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.
Upvotes: 23