如何使用java代码自动增加mongodb中的字段? [英] how can I auto increment a field in mongodb using java code?

查看:30
本文介绍了如何使用java代码自动增加mongodb中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有commentId"字段的评论表.我在这个领域创建了一个索引.我不知道如何插入新文档,并且 commentId 字段应该在为每个新文档插入时自动递增.有什么办法可以实现这个吗?

I have a comments table with a field "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. Is there any way I can implement this ?

推荐答案

MongoDB 自动为每个插入其中的对象创建一个 id.您无需创建自己的 ID.

MongoDB automatically creates an id for every object inserted into it. 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 列上放置索引.
  • 要在索引上插入文档查询以获得最高数字,请加 1,将其用作 id.
  • 如果由于重复索引重试导致插入失败

它涉及几次往返,但应该是健壮的,并且索引到位速度非常快.

It involves a few round trips but should be robust and with the index in place pretty fast.

如果您只有一个位置写入这些,您可以在本地兑现 AtomicInteger 中的 id,并且只有在检测到碰撞时才执行完整的往返过程,然后更新 AtomicInteger.

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.

这篇关于如何使用java代码自动增加mongodb中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆