iamyojimbo
iamyojimbo

Reputation: 4719

Keeping default mongo _id and unique index of MondoDB

Is it good or bad practice to keep the standard "_id" generated my mongo in a document as well as my own unique identifier such as "name", or should I just replace _id generated with the actual name so my documents will look like this:

{
    _id: 782yb238b2327b3,
    name: "my_name"
}

or just like this:

{
    _id: "my_name"
} 

Upvotes: 1

Views: 127

Answers (1)

andyewebb
andyewebb

Reputation: 80

This depends on the scenario, there is nothing wrong with having your own unique ID, it may be string or a number, completely depends on your situation as long as its unique, the important thing is you are in charge of it. You would want to add an index to it of course.

for example i have an additional ID field which is a number called 'ID', because i required a sequential number as an identifier, another usecase may be that your migrating an application so you have to conform to a particular sequence pattern.

The sequences for the unique identifies could easily be stored in a separate document/collections.

There is no issue with using the built in _id if you have no requirement not to have a custom one, an interesting fact is that you can get the created date out of the _id. Always useful.

db.col.insert( { name: "test" } );
var doc = db.col.findOne( { name: "test" } );
var timestamp = doc._id.getTimestamp();

Upvotes: 1

Related Questions