5

I have a document in mongodb that has been created from this java model:

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

class CommentDetailList
{
    String text;
    User user;
}

class User
{
    String userID;
    String username;
}

So, my document will look like this:

{
  "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"
        }
     }
  ]
}

Now I want to update username of user whose userID = 001 with this code:

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

The problem is it update only first comment (comment with text = "Hello Comment1").

Could anyone help me, please ?

Do I have misunderstand with the update function ?

Thx.

PS. Sorry for my english :D

1 Answer 1

8

Try this query:

Query query = new Query(new Criteria().andOperator(
  Criteria.where("pollID").is("ABCDEFG"),
  Criteria.where("commentDetailList").elemMatch(Criteria.where("user.userID").is("001"))
));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.