A logo showing the text blog.marcnuri.com
Español
Home»Java»Spring-data + Mongo: Auto-increment sequence in MongoDB using a Spring service

Recent Posts

  • Kubernetes MCP Server Joins the Containers Organization!
  • MCP Tool Annotations: Adding Metadata and Context to Your AI Tools
  • Fabric8 Kubernetes Client 7.2 is now available!
  • Connecting to an MCP Server from JavaScript using AI SDK
  • Connecting to an MCP Server from JavaScript using LangChain.js

Categories

  • Artificial Intelligence
  • Front-end
  • Go
  • Industry and business
  • Java
  • JavaScript
  • Legacy
  • Operations
  • Personal
  • Pet projects
  • Tools

Archives

  • July 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • August 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • February 2020
  • January 2020
  • December 2019
  • October 2019
  • September 2019
  • July 2019
  • March 2019
  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • August 2017
  • July 2017
  • January 2017
  • December 2015
  • November 2015
  • December 2014
  • March 2014
  • February 2011
  • November 2008
  • June 2008
  • May 2008
  • April 2008
  • January 2008
  • November 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007

Spring-data + Mongo: Auto-increment sequence in MongoDB using a Spring service

2017-08-21 in Java tagged Database / Java / Mongo / MongoDB / Sequence / Spring Framework / Spring Data by Marc Nuri | Last updated: 2021-03-18
Versión en Español

Introduction

In this article, I'll show you how to assign an automatically incremented sequence value to a field using a Mongo collection. We'll use the same technique shown in the mongodb.com tutorial but with pure Java methods.

This procedure is useful when you need to assign public or easily rememberable identifiers for users (invoice numbers, supplier numbers, shipment numbers, etc.).

It's important to note that this value should not be used as the unique document identifier—MongoDB already provides better ways to assign document IDs, and using this approach is generally considered bad practice. Also, in distributed systems or databases with a huge number of documents, this methodology should be avoided.

Code to safely update a sequence in MongoDB from Java
Code to safely update a sequence in MongoDB from Java

Sequence collection

Just like in the MongoDB tutorial, we'll have a @Document for each sequence we use. This document will store the last value used for each sequence.

For example, in JSON notation:

{
    "_id": "userid",
    "seq": 0
}

Let's create the following Java class:

Sequence.java
@Document(collection = "sequences")
public class Sequence {
  @Id
  private String id;
  private Long value;
  //....//
}

Next, we'll create a Spring service to safely get the next value for each sequence.

In the original tutorial, the following Javascript function is used:

function getNextSequence(name) {
   var ret = db.counters.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true
          }
   );

   return ret.seq;
}

We'll add this logic to a Spring @Service that can be used when saving a document that needs a sequence value:

SequenceService.java
@Service
public class SequenceService {
  @Autowired
  private MongoOperations mongo;

  //...//

  public Long getNextValue(String sequenceId) {
    //https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/
    final Sequence sequence = mongo.findAndModify(
        query(where("_id").is(sequenceId)),
        new Update().inc("value",1),
        options().returnNew(true).upsert(true),
        Sequence.class);
    return sequence.getValue();
  }
}

This function can then be used in another service or repository when saving a document (e.g. an invoice):

InvoiceService.java
@Service
public InvoiceService {

    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private InvoiceRepository invoiceRepository;

    //...//

    public Invoice insert(Invoice newInvoice) {
        //...//
        newInvoice.setPublicId(sequenceService.getNextValue("INV"));
        //...//
         return invoiceRepository.insert(newInvoice);
    }

    //...//

}

The findAndModify function

The main function used is findAndModify(), which modifies and returns a single document. It's important to apply the function by filtering on a field that uniquely selects the sequence. In this case, we locate the sequence by "_id".

The code snippet new Update().inc("value",1) will increment the "value" field by one.

The returnNew(true) option makes the function return the new document instead of the original.

The upsert(true) option creates a new document if the specified sequence doesn't exist yet.

Download source code

You can find a sample project with the code shown in this tutorial, including a @RestController to retrieve sequence values and a unit test to verify correct generation and storage, at the following link:

https://github.com/marcnuri-demo/spring-mongo-sequences

Twitter iconFacebook iconLinkedIn iconPinterest iconEmail icon

Post navigation
Docker container as a Linux system serviceAngular + Spring Boot integration using Gradle
© 2007 - 2025 Marc Nuri