In mongodb i have a field that must be from 0 to MAX
(an integer final variable). every time the value hits MAX
it must return to 0. to perform this i tried this (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?
You could perform two requests : reset the counter to 0 of it is equal to MAX. Then increase the counter by one. All this using mongodb mechanism such as findAndModify, which guarantees atomicity !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.