【问题标题】:how to update nested objects in array that match the condition in spring data - mongodb?如何更新与spring数据中的条件匹配的数组中的嵌套对象-mongodb?
【发布时间】:2013-04-10 14:10:12
【问题描述】:

我在 mongodb 中有一个从这个 java 模型创建的文档:

class Comment 
{ 
    String pollID; 
    List<CommentDetail> commentDetailList;
}

class CommentDetailList
{
    String text;
    User user;
}

class User
{
    String userID;
    String username;
}

所以,我的文档将如下所示:

{
  "pollID":"ABCDEFG",
  "commentDetailList":
   [
     {
        "text":"Hello Comment1",
        "user":
        {
           "userID":"001",
           "username": "username1"
        }
     },
     {
        "text":"Hello Comment2",
        "user":
        {
           "userID":"001",
           "username": "username1"
        }
     },
     {
        "text":"Hello Comment3",
        "user":
        {
           "userID":"002",
           "username": "username2"
        }
     }
  ]
}

现在我想用以下代码更新 userID = 001 的用户的用户名:

Query query = new Query(Criteria.where("pollID").is("ABCDEFG")
            .and("commentDetailList")
            .elemMatch(Criteria.where("user.userID").is("001")));

Update update = new Update().set("commentDetailList.$.user.username", username);

WriteResult wr = mongoTemplate.updateMulti(query, update, "comment");

问题是它只更新第一条评论(带有 text = "Hello Comment1" 的评论)。

有人可以帮帮我吗?

我对更新功能有什么误解吗?

谢谢。

PS。对不起我的英语:D

【问题讨论】:

    标签: mongodb spring-data-mongodb


    【解决方案1】:

    试试这个查询:

    Query query = new Query(new Criteria().andOperator(
      Criteria.where("pollID").is("ABCDEFG"),
      Criteria.where("commentDetailList").elemMatch(Criteria.where("user.userID").is("001"))
    ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2023-04-03
      • 2013-12-26
      • 1970-01-01
      相关资源
      最近更新 更多