MongoDB UpdateFirst方法的用法 [英] MongoDB UpdateFirst Method Usage
本文介绍了MongoDB UpdateFirst方法的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用MongoTemplate的UpdateFirst()更新内部文档.但是更新操作失败.
I am using MongoTemplate's UpdateFirst() to update the inner document. But the update operation is failing.
我的Mongo收藏结构:
my Mongo Collection Structure:
{
"_id" : ObjectId("540dfaf9615a9bd62695b2ed"),
"_class" : "com.springpoc.model.Awards",
"brand" : [
{
"name" : "Brand1",
"descr" : "Desc1"
}
],
"name" : "Award1",
"narname" : "Nar1"
}
Java代码:
mongoTemplate.updateFirst(
query(where("name").is("Award1")),
Update.update("brand.$.descr", "Desc2"),
Awards.class);
奖励类结构
public class Awards {
private String id;
List<Brand> brand = new ArrayList<Brand>();
private String name;
private String narname;
品牌类别结构
public class Brand {
private String name;
private String descr;
有关如何将文档"Brand.Name"更新为新值的任何建议.
Any suggestions on how to update the document "Brand.Name" to new value.
推荐答案
如果要在更新部分中使用运算符$
,则必须在查询部分中显式编写that array
.因此,
If you want to use operator $
in update portion, you have to explicitly write that array
in the query portion. So,
mongoTemplate.updateFirst(
query(where("name").is("Award1")),
Update.update("brand.$.descr", "Desc2"),
Awards.class);
应该是
mongoTemplate.updateFirst(
query(where("name").is("Award1"))
.and("brand.name").is("Brand1"), // "brand" in "brand.name" is necessary, others according to your requirement
Update.update("brand.$.descr", "Desc2"),
Awards.class);
如果您知道元素在数组中的位置,则不必使用$,您可以尝试如下操作:
If you know the position of element in array, `$' is unnecessary, you can try like this:
mongoTemplate.updateFirst(
query(where("name").is("Award1")),
Update.update("brand.0.descr", "Desc2"), // 0 is the index of element in array
Awards.class);
以相同的方式处理name
字段.
Same way to handle name
field.
这篇关于MongoDB UpdateFirst方法的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文