24

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

Community
  • 1
  • 1
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • Can you clarify the question by providing what the docs do not answer for you: http://www.mongodb.org/display/DOCS/Object+IDs – Rob Olmos Nov 14 '10 at 09:58

3 Answers3

22

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.

Niels van der Rest
  • 31,664
  • 16
  • 80
  • 86
  • 4
    How else should I compare it to other strings, if I don't use the ObjectID as the unique identifier? – TIMEX Nov 14 '10 at 20:06
  • @TIMEX: What do you mean? Could you update your question to explain exactly what you're trying to achieve? – Niels van der Rest Nov 14 '10 at 20:40
  • 4
    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.) I'm building a blog, and I want it to work with HTTP GET. view?uid=e93jfsb0e3jflskdjf – TIMEX Nov 14 '10 at 21:11
17

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.

Gates VP
  • 44,957
  • 11
  • 105
  • 108
0

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.

Meekohi
  • 10,390
  • 6
  • 49
  • 58