Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store _Id as object or string in MongoDB?

Tags:

I am developing an API using Codeigniter and MongoDB. In this system I am saving the full name and _ID of users that the selected user is following.

What is best to do regarding the _Id? Store it as an object or as a string? If I store it as an object I need to convert it to string when echoing out followers otherwise the output looks strange.

My question is really. Is it ok to store the _Id as a string rather than an object? What is the downside of storing as string?

Thankful for all input!

like image 664
Jonathan Clark Avatar asked Oct 14 '11 08:10

Jonathan Clark


People also ask

Can _id in MongoDB be a string?

Yes, you can use a string as your _id.

What is the type of _id in MongoDB?

Architecturally, by default the _id field is an ObjectID, one of MongoDB's BSON types. The ObjectID is the primary key for the stored document and is automatically generated when creating a new document in a collection.

What is datatype of _id?

The _id is the default key that is generated to uniquely identify each document in the collection. The 12-byte ObjectId, which is a hexadecimal string value consists of: a 4-byte value representing the seconds since the Unix epoch, a 3-byte machine identifier, a 2-byte process id, and.

Should I use _id in MongoDB?

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.


1 Answers

Performance for requests (and updates) are really better with objectid. More over, objectid are quite small in space.

From the official doc :

BSON includes a binary data datatype for storing byte arrays. Using this will make the id values, and their respective keys in the _id index, twice as small.

here are 2 links that can help you : - http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs - http://www.mongodb.org/display/DOCS/Object+IDs

like image 105
kamaradclimber Avatar answered Sep 17 '22 19:09

kamaradclimber