spring-data-mongodb嵌套文档投影
spring-data-mongodb nested document projection
我有 posts 集合,其中包含嵌套文档 comments。简单的文档架构如下所示:
{
"_id" : ObjectId("5867e5e64f768509c59f9392"),
"userId" : 1,
"comments": [
{
"id" : 1,
"text": "a"
},
{
"id" : 2,
"text": "b"
}
]
}
我只想投影请求的评论。我找到了一个可接受的解决方案。 (也欢迎只评论对象return解决方法)
> 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 有更好的方法吗?
您的@Query json 格式错误。
试试这个。
@Query( value="{ 'userId' : ?0 , 'comments.id': ?1 }", fields = "{ 'comments.$' : 1}")
我有 posts 集合,其中包含嵌套文档 comments。简单的文档架构如下所示:
{
"_id" : ObjectId("5867e5e64f768509c59f9392"),
"userId" : 1,
"comments": [
{
"id" : 1,
"text": "a"
},
{
"id" : 2,
"text": "b"
}
]
}
我只想投影请求的评论。我找到了一个可接受的解决方案。 (也欢迎只评论对象return解决方法)
> 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 有更好的方法吗?
您的@Query json 格式错误。
试试这个。
@Query( value="{ 'userId' : ?0 , 'comments.id': ?1 }", fields = "{ 'comments.$' : 1}")