在我的项目中,我使用的是SpringBoot 1.3.2和org.springframework.data.mongodb.core.query.*
我正在尝试更新数组中的元素,在我的主对象中我有这样的数组:
"sections" : [
{
"sectionId" : "56cc3c908f5e6c56e677bd2e",
"name" : "Wellcome"
},
{
"sectionId" : "56cc3cd28f5e6c56e677bd2f",
"name" : "Hello my friends"
}
]
Run Code Online (Sandbox Code Playgroud)
使用Spring我想用sectionId 56cc3c908f5e6c56e677bd2e更新记录的名称
我试图这样做,但它不起作用
Query query = Query.query(Criteria
.where("sections")
.elemMatch(
Criteria.where("sectionId").is(editedSection.getId())
)
);
Update update = new Update().set("sections", new BasicDBObject("sectionId", "56cc3c908f5e6c56e677bd2e").append("name","Hi there"));
mongoTemplate.updateMulti(query, update, Offer.class);
Run Code Online (Sandbox Code Playgroud)
它创造了类似于:
"sections" : {
"sectionId" : "56cc3c908f5e6c56e677bd2e",
"name" : "Hi there"
}
Run Code Online (Sandbox Code Playgroud)
但上面是对象{}我想要一个数组[],我不希望它删除其他元素.
任何机构都可以帮我更新如何使用Spring更新sectionId 56cc3c908f5e6c56e677bd2e的记录名称
chr*_*dam 11
您基本上想要复制此mongo shell更新操作:
db.collection.update(
{ "sections.sectionId": "56cc3c908f5e6c56e677bd2e" },
{
"$set": { "sections.$.name": "Hi there" }
},
{ "multi": true }
)
Run Code Online (Sandbox Code Playgroud)
等效的Spring Data MongoDB代码如下:
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Update;
...
WriteResult wr = mongoTemplate.updateMulti(
new Query(where("sections.sectionId").is("56cc3c908f5e6c56e677bd2e")),
new Update().set("sections.$.name", "Hi there"),
Collection.class
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7058 次 |
| 最近记录: |