Java MongoDB – Auto Sequence ID example

In this tutorial, we will show you how to generate an auto-incrementing sequence id in MongoDB using Java. Here is the clean example and we will implement it in java.

Tools Used

  1. Mongodb version :  3.2.8
  2. Mongo Java driver : 3.3.0
  3. Java version: 1.7
  4. Eclipse : 4.5

Maven dependency


Java Example

package com.programtalk.example.mongo;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class SequenceExample {
	private final static String DB_NAME = "testdb";
	private final static String MY_SEQUENCE_COLLECTION = "mySequnceCollections";
	private final static String MY_SEQUENCE_NAME = "personId";

	public static void main(String[] args) {
		MongoClient mongoClient = new MongoClient();
		MongoDatabase database = mongoClient.getDatabase(DB_NAME);
		Object nextSequence = getNextSequence(MY_SEQUENCE_NAME, database);
	private static void createCountersCollection(MongoCollection&amp;amp;amp;lt;Document&amp;amp;amp;gt; countersCollection) {

	    Document document = new Document();
	    document.append("_id", MY_SEQUENCE_NAME);
	    document.append("seq", 1);

	public static Object getNextSequence(String name, MongoDatabase database) {
		MongoCollection&amp;amp;amp;lt;Document&amp;amp;amp;gt; countersCollection = database.getCollection(MY_SEQUENCE_COLLECTION);
		if (countersCollection.count() == 0) {
	    Document searchQuery = new Document("_id", name);
	    Document increase = new Document("seq", 1);
	    Document updateQuery = new Document("$inc", increase);
	    Document result = countersCollection.findOneAndUpdate(searchQuery, updateQuery);

	    return result.get("seq");


Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.