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.
Starting in MongoDB
v4.2
, thedb.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"]}}}
]
)
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.