Is there a way to achieve the following:-
MyDocument {
String docId;
Integer bal;
Set<String> actions;
}
I need to update the field actions with some value of a user action, say from
[a1, a2]to
[a1, a2, a3]At the same time, this added action can increment the
balby some value so I need to ensure that$incoperation is also implemented for thebalfield.
One way of achieving this I could think of was incrementing the bal using one update query :
Bson searchFilter = Filters.in("docId", <someId>);
// couldn't find a cleaner way of increment in mongo-java
BasicDBObject modifiedObject = new BasicDBObject();
modifiedObject.put("$inc", new BasicDBObject().append("bal",2)); // any value to increment
mongoCollection.updateOne(searchFilter, modifiedObject);
I can thereafter execute another update document query for set of actions update.
Another way could possibly have been updating the documents with both the fields. For which :
- I would have to
findthe document first, read the currentbal, perform the compute at application. - Then
updatethe document with both the computed fields.
In both the above approaches, I couldn't see a way of avoiding to query the DB twice. Is there any other workaround possible to achieve this currently?
Also, I am concerned about the atomicity with the above combination of [UPDATE + UPDATE] or [GET + UPDATE], given multiple such concurrent queries can occur, is the concern justified even?
Do let me know any further detail required.