Update string field concatenating another string in mongodb with spring-data

Viewed 933

How I can update a string field in a mongo document, concatenating another string value, using java and spring-data mongo? Ex:

{
    “languages”: “python,java,c”
}

Concat “kotlin”:

{
    “languages”: “python,java,c,kotlin”
}

Thanks so much.

1 Answers

Starting in MongoDB v4.2, the db.collection.update() method can accept an aggregation pipeline to modify a field using the values of the other fields in the Document.

Update with Aggregation Pipeline

Try this one:

UpdateResult result = mongoTemplate.updateMulti(Query.query(new Criteria()),
    AggregationUpdate.update()
        .set(SetOperation.set("languages")
                .toValue(StringOperators.Concat.valueOf("languages").concat(",").concat("kotlin"))),
    "collection"); //mongoTemplate.getCollectionName(Entity.class)
System.out.println(result);
//AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}

In MongoDB shell, it looks like this:

db.collection.updateMany({},
  [
    { "$set" : { "languages" : { "$concat" : ["$languages", ",", "kotlin"]}}}
  ]
)
Related