【问题标题】:MongoDB UpdateFirst Method UsageMongoDB UpdateFirst 方法用法
【发布时间】:2014-09-09 10:13:11
【问题描述】:

我正在使用 MongoTemplate 的 UpdateFirst() 来更新内部文档。但更新操作失败。

我的 Mongo 集合结构:

{
"_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”更新为新值的任何建议。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    如果您想在更新部分使用运算符$,您必须在查询部分显式写入that array。所以,

    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);
    

    如果你知道数组中元素的位置,`$' 是不必要的,你可以这样尝试:

    mongoTemplate.updateFirst(
    query(where("name").is("Award1")), 
    Update.update("brand.0.descr", "Desc2"), // 0 is the index of element in array
    Awards.class);
    

    处理name 字段的方法相同。

    【讨论】:

    • 这很好用。我的错误是我的查询中的 AND 条件丢失。我也可以使用 FINDONE 和 SAVE 的组合来更新相同的内容。
    • @karthik damu,也许using combination of FINDONE and SAVE 会产生另一个非原子问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多