我想在 mongoDB 内的现有字段中附加一个值。假设我定义了一个 mongoDB 数据库,其中包含一个 Person 集合,并且该 Person Document 如下所示:
{
"_id": {
"$oid": "64d4b688638bed43641ca2fb"
},
"email": "gvvg@gv",
"contact": {
"address": "vffv",
"age": 22,
"brand": null,
"email": "gvvg@gv",
"name": "Bruce"
}
}
我正在我的 Spring Boot 应用程序中运行一个查询,如下所示,以便它可以将新值附加到字段“名称”内的现有值。 就像我想运行一个查询,其中“Wayne”被附加到“name”字段,以便存储在 mongo 中的最终数据将是“Bruce Wayne”。
请让我知道在 Spring Boot 中使用 mongo 的查询和更新是否可以实现上述操作?
我尝试了下面的代码,但它附加了数组并且不起作用。
update.set(
"name",
new Document("$concat",
List.of(
"name" +
"wayne"
)));
您需要的是流水线更新。
db.collection.update(
{},
[
{$set:
{"contact.name": {$concat: ["$contact.name"," Wayne"]}}
}
]
);
在SpringBoot中,
Query query = Query.query(<your filter criteria>);
AggregationUpdate update = Aggregation.newUpdate()
.set("contact.name").toValue(
StringOperators.Concat.valueOf("contact.name").concat(" Wayne")
);
mongoTemplate.updateMulti(query, update, <your collection>.class);