Andrei
Andrei

Reputation: 115

MongoDB with Spring Data find object in array by id

I am using Spring Data with a Mongo DB embedded database and have the following document structure:

{
  id : 111
  messaage : abcd
  commentsList: [
                  {
                    id : 123
                    text: test text
                    numberOfLikes : 5
                    numberOfDislikes: 2
                  }
                ]     
}

I am trying to get a comment by id and update the numberOfLikes field by one and can't seem to get it to work, here is what I've tried and the java class structure:

public class Post {

    private String id;
    private String message;
    private List<Comment> commentsList = new ArrayList<>();
    ...
}

public class Comment {

    private String id;
    private String text;
    private int numberOfLikes;
    private int numberOfDislikes;

    ...
}

Query query = new Query();
query.addCriteria(Criteria.where("commentsList._id").is("123"));
List<MongoComment> commentList = mongoTemplate.find(query, MongoComment.class);

Currently the returned list is always null.

Upvotes: 1

Views: 7889

Answers (2)

chridam
chridam

Reputation: 103445

Since you are trying to get a comment by id and update the numberOfLikes field by one, you essentially want to replicate this mongo shell update operation:

db.post.update(
    { "commentsList.id": "123" },
    {
        "$inc": { "commentsList.$.numberOfLikes": 1 }
    }
)

The equivalent Spring Data MongoDB code follows:

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Update;

...

WriteResult wr = mongoTemplate.updateMulti(
    new Query(where("commentsList.id").is("123")),
    new Update().inc("commentsList.$.numberOfLikes", 1),
    MongoPost.class
);

Upvotes: 1

J. Carlos Calvo
J. Carlos Calvo

Reputation: 21

The id of the elements in the array "commentsList" is "id" (without the '_').

query.addCriteria(Criteria.where("commentsList.id").is("123"))

That should work.

The "_id" you're trying to query is the identifier Mongodb automatically generates for each document. Your document in the database looks like this:

{
  _id: ObjectId("56b46e1d1d1353e38886dcc34f"),
  id : 111,
  messaage : "abcd",
  commentsList: [
                  {
                    id : 123,
                    text: "test text",
                    numberOfLikes : 5,
                    numberOfDislikes: 2
                  }
                ]     
    }

Upvotes: 0

Related Questions