[英]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: 我将Spring Data与Mongo DB嵌入式数据库一起使用,并且具有以下文档结构:
{
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: 我正在尝试通过id获取评论,并通过一个更新numberOfLikes字段,但似乎无法使其正常工作,这是我尝试过的内容以及java类结构:
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. 当前,返回的列表始终为null。
The id of the elements in the array "commentsList" is "id" (without the '_'). 数组“ commentsList”中元素的id为“ id”(不带“ _”)。
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. 您要查询的“ _id”是Mongodb为每个文档自动生成的标识符。 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
}
]
}
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: 由于您尝试通过id
获取注释,并以一个值更新numberOfLikes
字段,因此,您实质上想复制此mongo shell更新操作:
db.post.update(
{ "commentsList.id": "123" },
{
"$inc": { "commentsList.$.numberOfLikes": 1 }
}
)
The equivalent Spring Data MongoDB code follows: 等效的Spring Data MongoDB代码如下:
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
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.