Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: is it possible to avoid using automatic _id field?

Tags:

c++

mongodb

I have a unique ID field of type int in my documents. I'm doing ensureIndex on this field, but my documents still contain _id. Can I get rid of it?

like image 290
Violet Giraffe Avatar asked Nov 11 '11 22:11

Violet Giraffe


2 Answers

From the docs ...

If a user tries to insert a document without providing an _id field, the database will automatically generate an object id and store it the _id field.

However, you can assign your own value to _id ...

The _id value may be of any type, other than arrays, so long as it is a unique.

The better question is why would you create your own unique ID, build an index on it and remove the very useful ObjectID _id that is auto indexed?

All the official drivers use ObjectID and it has a lot of really good aspects to it:

  • It has a timestamp built in (so you don't need to store a date field in your document, and you can use it to order by date.)

  • It is a "global, uniformly increasing sequence number" --- i.e. it'll still be unique across servers if you need to shard your data, etc.

like image 134
Justin Jenkins Avatar answered Oct 13 '22 21:10

Justin Jenkins


No, you can't get rid of it, it is there by design, but you can map your unique identifier int to the _id itself when inserting documents.

like image 41
plaes Avatar answered Oct 13 '22 21:10

plaes