title: creating an auto increment field within a mongo document
body: <p>In my Spring Boot application I am using Spring-Data MongoDB, and I have a simple POJO that represents users:</p>
  
  <pre><code>@EqualsAndHashCode
  public class User implements Storable {
  
    @Id
    public ObjectId id;
  
    @Getter @Setter public String firstName;
    @Getter @Setter public String lastName;
    @Getter @Setter public long userNum;
    @DBRef(lazy = true)
    @Getter @Setter public List&lt;Section&gt; sections = new ArrayList&lt;Section&gt;();
  
  ... 
  rest of class omitted
  ...
  
  }
  </code></pre>
  
  <p>my UserController looks something like this:</p>
  
  <pre><code>@Controller
  public class UserController {
  
    @Autowired
    UserRepository repository;
  
    @ModelAttribute("allSections")
    public List&lt;Section&gt; getSections() {
      return sectionRepository.findAll();
    }
  
    @RequestMapping(value = "/users/new", method = RequestMethod.POST)
    public String newUser(@ModelAttribute("user") User user) {
      User newUser = new User();
      newUser.userNum = user.userNum;
      newUser.firstName = user.firstName;
      newUser.lastName = user.lastName;
      newUser.sections = user.sections;
      newUser = repository.save(newUser);
  
      for (Section section : newUser.sections) {
        section.addToUsers(newUser);
        sectionRepository.save(section);
      }
  
      return "redirect:/users";
    }
  ... rest of controller omitted 
  }
  </code></pre>
  
  <p>please notice that the field that I want to be auto-generated is not the ID field.</p>
  
  <p>I would like for the <code>userNum</code> attribute to be auto incrementing such that the first user object created and stored in the database starts at a certain value... say 9000 and each user created after that is incremented by 1. </p>
  
  <p>What are my options to do this? I have seen examples using JPA's @GeneratedValue, others that rely on custom Mongo queries to create a sequence collection, but I have not been able to get either to work...</p>