我有帖子集合,其中包含嵌套文档评论。简单的文档架构如下所示:
{
"_id" : ObjectId("5867e5e64f768509c59f9392"),
"userId" : 1,
"comments": [
{
"id" : 1,
"text": "a"
},
{
"id" : 2,
"text": "b"
}
]
}
我想只投影所请求的评论。我找到了一个可以接受的解(也欢迎评论对象返回解决方案)
> db.posts.find({userId: 1, 'comments.id': 1}, {'comments.$': 1});
{ "_id" : ObjectId("5867e5e64f768509c59f9392"), "comments" : [ { "id" : 1, "text" : "a" } ] }
然后我尝试将它应用于带有查询注释的mongodb存储库接口。
@Query(
value = ""
+ "{"
+ " 'userId' : '?1',"
+ " 'comments.id': '?2',"
+ "}",
fields = "'comments.$'"
)
Note findComment(String userId, String commentId);
但是我得到了施放异常。使用spring-data-mongodb有更好的方法吗?
答案 0 :(得分:1)
你的@Query json生病了。
试试这个。
@Query( value="{ 'userId' : ?0 , 'comments.id': ?1 }", fields = "{ 'comments.$' : 1}")