MongoDB auto-generated id with spring boot

In this project we are going to see how we can auto generate id in mongo db with spring boot.

we are going to create a simple spring boot project with mongodb.


add the following dependencies in your spring boot application’s pom.xml


Project structure

MongoDB auto-generated id with spring boot

let’s create our model class. inside this class make your id data type String otherwise, you can’t auto-generate id with MongoDB irectly

package com.gangforcode.autoId.mode;

@Document(collation = "data")
public class Data {

    private String id;
    private String name;

    public Data(String id, String name) { = id; = name;

    public void setName(String name) { = name;

    public String getId() {
        return id;

    public void setId(String id) { = id;

    public String getName() {
        return name;

    public Data() {

Here @Id will autogenerate values only for the string field but it will not auto increment values.

now create a repository interface by extending MongoRepository

package com.gangforcode.autoId.repo;

import com.gangforcode.autoId.mode.Data;
import org.springframework.stereotype.Repository;

public interface RepositoryMongo extends MongoRepository<Data,String> {

time for creating controller class , inside controller auto wire mongoRepo

package com.gangforcode.autoId.controller;

import com.gangforcode.autoId.mode.Data;
import com.gangforcode.autoId.repo.RepositoryMongo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

public class controllerMongo {
    RepositoryMongo repo;

    public ResponseEntity<?> reg(@RequestBody Data data)
        return new ResponseEntity<>(, HttpStatus.CREATED);


Configuration for database connectivity

add following configuration in according to your database =  localhost = 27017 = tests

Now you can check the “/reg” endpoint only giving name and id will be auto generated

now ID is auto-generated but it will not work with int or other data types for auto-generation. For auto increment in Mongodb for int and other data types, you check our others tutorials

Thanks for more tutorial check our website

1 thought on “MongoDB auto-generated id with spring boot”

Leave a Comment