Nyamiou The Galeanthrope
Nyamiou The Galeanthrope

Reputation: 1214

Using functional id with MongoDB

Alright, so I was defining a document model for a MongoDB database and my colleagues told me that we shouldn't use functional id for the "_id" field and that we should only use an auto generated ObjectId.

I don't understand why when I already have an unique id and another field to store a timestamp, from my point of view we are wasting time creating an useless index because in our case the generated id will never be used.

But I want to be sure since I'm a NoSQL noob, so:

Do you know any problems that could arise by having a functional id as the "_id" of a MongoDB collection?

Is there is any real advantages of using an auto generated ObjectId instead of a functional id for the "_id" field?

In case we want to migrate from MongoDB to some other database later, can the ObjectId be an advantage or a disadvantage?

Upvotes: 0

Views: 333

Answers (1)

Enrique GP
Enrique GP

Reputation: 11

In order of appearance:

  1. Do you know any problems that could arise by having a functional id as the "_id" of a MongoDB collection?

The _id is a unique field for every document inside a collection. Only problem that could arise with a functional id as the _id field is duplicates and logically, failure at the moment of insertion. For that reason I would suggest keeping an eye on how you generate the _id in your function to guarantee its uniqueness. Please check the MongoDB documentation for further details about ObjectID as your use case could benefit of using it to generate the _id field.

  1. Is there is any real advantages of using an auto generated ObjectId instead of a functional id for the "_id" field?

This relates with your first question and there is a straightforward answer to this: an auto generated ObjectID within a collection for any inserted document will lower the risk of duplicate entries as opposed to a function-generated key.

  1. In case we want to migrate from MongoDB to some other database later, can the ObjectId be an advantage or a disadvantage?

This depends on the nature of the database you are migrating to and its data model so there is no straightforward answer to this one. MongoDB will guarantee that the document within the collection will have a unique _id and you should be aware of this fact at the moment of migration to other database system.

Upvotes: 1

Related Questions