简体   繁体   English

java mongodb-仅在范围内设置字段

[英]java mongodb - set a field only if it is in range

In mongodb i have a field that must be from 0 to MAX (an integer final variable). 在mongodb中,我有一个必须从0到MAX (整数最终变量)的字段。 every time the value hits MAX it must return to 0. to perform this i tried this (java): 每次值达到MAX它都必须返回0。要执行此操作,我尝试了此操作(java):

Document document = coll.findOneAndUpdate(
    filter,
    new Document(//update
        "$inc",
        new Document("counter", 1)
     )
);
int count = (document != null) ? document.getInteger("counter") : 0;
if(count >= MAX) {
    count-= MAX;
    coll.updateOne(filter, new Document("$set", new Document("counter", count));
}

the only problem is that this is not synchronized, and can cause the counter to lose some counts if multiple clients access this at the same time. 唯一的问题是,这是不同步的,如果多个客户端同时访问此计数器,则可能导致计数器丢失一些计数。 to make this synchronized i must test that count is in range from count to max before setting it, how can i achieve this? 为了使此同步,我必须先测试该count在从countmax范围内,然后再设置它,我如何实现这一点?

You could perform two requests : reset the counter to 0 of it is equal to MAX. 您可以执行两个请求:将计数器重置为0等于MAX。 Then increase the counter by one. 然后将计数器增加一。 All this using mongodb mechanism such as findAndModify, which guarantees atomicity ! 所有这些都使用mongodb机制(例如findAndModify)来保证原子性!

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

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