Last updated: 2022-03-20

  1. Learn
  2. MongoDB
  3. Generating IDs

Generating IDs in Spring Data MongoDB using Sequences

It is often desirable to automatically assign primary keys following a sequence. This article will describe the setup to enable this feature in our Spring Boot application.

In general, we can assign any primary key to our document ourselves. So if we set the id of our document with setId(...), MongoDB will directly use this value.

Example of assigning a random primary key

Sequence setup

To assign the value following a sequence, we first create a collection in which the current value is stored and incremented.

In addition we need a service providing the sequence value. The getNextValue() method returns and increments the current value and, if necessary, creates the sequence once if it does not already exist. Our sequence here starts at 10000 to reserve values below that for fixed ids.

EntityListener setup

Finally, we need an EventListener for our document. By linking to BeforeConvertEvent, a primary key is automatically assigned to our new document before persisting it to MongoDB. With this, our sequence setup is complete and ready to be used.

In the Free plan of Bootify you can create a Spring Boot application for MongoDB. The database schema can be freely defined and the setup including listeners is automatically generated.

Learn more
or see pricing