Auto Incrementing Field On Spring Data MongoDB

MongoDB came with all sophisticated ObjectId generation feature, but often you just jumped the ship from relational database, and you still want an easy to read / communicate numeric identifier field which automatically increments every time new record is inserted.

One neat suggestion from MongoDB tutorial is to use a counter collection with a ‘counter name’ as its id, and a ‘seq’ field to store the last used number:

  _id: "users",
  seq: 0

Then use findAndModify function to increment and obtain the next value.

	query: { _id: name },
	update: { $inc: { seq: 1 } },
	new: true

When developing using Spring Data MongoDB, this neat trick can be written as a simple service. Here I used the collection name as the counter name so it’s easy to guess / remember.

import static*;
import static*;
import static*;

public class CounterService {
  @Autowired private MongoOperations mongo;
  public int getNextSequence(String collectionName) {

    Counter counter = mongo.findAndModify(
      new Update().inc("seq", 1),
    return counter.getSeq();

Counter is just a simple class representing the collection. Please beware the usage of int data type, this will limit to 2^31 entries maximum.

@Document(collection = "counters")
public class Counter {
  @Id private String id;
  private int seq;
  /* getters & setters .. */

Then when inserting a new entry (with help of Spring MongoDB Repository support), just set the id field like this before you save it

User newUser = new User();

You’ll get an incrementing simple numeric id each time you insert new object


One thought on “Auto Incrementing Field On Spring Data MongoDB

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s