Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update nested objects in array that match the condition in spring data - mongodb?

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

like image 202
kp_ping Avatar asked Mar 25 '23 07:03

kp_ping


1 Answers

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"))
));
like image 195
Jayz Avatar answered Apr 05 '23 21:04

Jayz