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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With