简体   繁体   English

如何使用Java代码在mongodb中自动增加字段?

[英]how can I auto increment a field in mongodb using java code?

I have a comments table with a field "commentId". 我有一个带有“ commentId”字段的注释表。 I created an index on this field. 我在此字段上创建了一个索引。 I am not getting how to insert a new document and the commentId field should automatically increment itself upon insertion for every new document. 我没有得到如何插入新文档的信息,并且在为每个新文档插入时,commentId字段应自动递增。 Is there any way I can implement this ? 有什么办法可以实现呢?

MongoDB automatically creates an id for every object inserted into it. MongoDB自动为插入其中的每个对象创建一个ID。 You don't need to create your own id. 您无需创建自己的ID。

If you do need an incrementing integer id then you run into all sorts of distributed synchronization issues - it's actually quite hard to get right for non-trivial cases. 如果确实需要递增的整数id,那么您会遇到各种各样的分布式同步问题-实际上,很难解决不重要的情况。

To generate a unique id the simplest way I can think of: 要生成唯一的ID,我可以想到的最简单的方法是:

  • put an index on the id column with a unique constraint. 将索引放在具有唯一约束的id列上。
  • to insert a document query on the index for the highest number, add 1, use that as id. 要在索引上插入编号最高的文档查询,请加1,并将其用作ID。
  • if insert fails due to duplicate index retry 如果由于重复的索引重试而导致插入失败

It involves a few round trips but should be robust and with the index in place pretty fast. 它涉及一些往返,但是应该健壮并且索引很快就可以实现。

If you only have one location writing these you can cash the id in an AtomicInteger locally and only do the full round trip process if you detect a collision then update the AtomicInteger. 如果只有一个位置写这些位置,则可以在本地将AtomicInteger中的ID兑现,并且如果检测到碰撞,则仅执行完整的往返过程,然后更新AtomicInteger。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM