【问题标题】:How to auto increment mongo db in Spring Boot?如何在 Spring Boot 中自动增加 mongo db?
【发布时间】:2019-04-18 23:16:24
【问题描述】:

我在 Spring Boot 中使用 Mongodb 尝试简单的 CRUD。我的身份证号码有问题。如何自动增加 id。 I tried but couldn't do it

有没有简单的自增方式?

控制器

@Autowired
EmployeeRepo repo;

@RequestMapping(value = "home", method = RequestMethod.GET)
public String getHomePage(Model model) {

    Employee employee = new Employee();

    employee.setId(1);
    employee.setName("deniz");
    employee.setPassword("123");

    repo.save(employee);  

    ...

员工

@Document(collection = "Employee")
public class Employee {

@Id
private long id;

private String name;
private String password; 

// getter and setter

【问题讨论】:

  • @alexbt 没错。当我尝试使用 ObjectId 而不是 Long 时问题解决了。因为“_id”中的集合是唯一的。无需自动递增。感谢您的评论,对不起我的英语不好:)

标签: mongodb spring-boot


【解决方案1】:
  public long getNextSequenceId(String key) {

    Query query = new Query(Criteria.where("_id").is(key));

        Update update = new Update();
    update.inc("seq", 1);

    FindAndModifyOptions options = new FindAndModifyOptions();
    options.returnNew(true);

    SequenceId seqId = 
            mongoOperation.findAndModify(query, update, options, SequenceId.class);

    return seqId.getSeq();

  } 

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 2021-03-25
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 2020-09-07
    • 2021-10-02
    • 1970-01-01
    • 2013-01-05
    相关资源
    最近更新 更多