Search code examples
javamongodbmongodb-update

MongoDB Java - UpdateMany() with both an $inc operator and $concat aggregation


JavaVersion: 11 --- MongoDB-driver: 4.6.1

I'm wondering if it is possible to implement a bulk update method that would increment the document version through the $inc operator while simultaneously making it possible to concatenate a string to a field value through $concat aggregation.

I've tried some workarounds, but I cannot manage the whole thing to work, in particular:

  1. Combining all the operators in a single Bson with Updates::combine -> $concat and $inc works independently, but combining both of them I get this error: "A pipeline stage specification object must contain exactly one field."

  2. Passing a List of Bson to "updateMany() -> I get no error, but $concat does not work as expected, in the DB I have something like:

    "field1": {"$concat": ["$field1", "_OK"]},
    

In order to make $concat work I use this (according to the documentation):

        Updates.set(new Document("$concat", Arrays.asList(
            new BsonString(String.format("$%s", key)),
            new BsonString(value))));

While for $inc I'm using the Updetes.inc() method.


Solution

  • Solved

    As pointed out by prasad_ in the comments, you can't combine update operators with pipeline ones. To solve the issue, I've used a List of BSON using $add aggregation instead of the $inc operator.

    An implementation idea for the $add operator.

    Updates.set(key, new Document("$add", Arrays.asList(
                    new BsonString(key),
                    value)));