Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Tags:

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

like image 763
TIMEX Avatar asked Nov 14 '10 08:11

TIMEX


People also ask

Is MongoDB object ID unique?

MongoDB is a NoSQL database that operates with collections and documents. Each document created on MongoDB has a unique object ID property. So when creating a document without entering an ID, the document will be created with an auto-generated ID.

What is the use of object ID?

An object identifier (OID) is an unambiguous, long-term name for any type of object or entity. The OID mechanism finds application in diverse scenarios, particularly in security, and is endorsed by the International Telecommunication Union (ITU), the Internet Engineering Task Force (IETF), and ISO.

How is MongoDB object ID generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

What is the object ID in MongoDB?

An ObjectId is a 12-byte BSON type having the following structure − The first 4 bytes representing the seconds since the unix epoch. The next 3 bytes are the machine identifier. The next 2 bytes consists of process id. The last 3 bytes are a random counter value.


1 Answers

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.

like image 172
Niels van der Rest Avatar answered Oct 21 '22 11:10

Niels van der Rest