Reputation: 6003
I have posts collection with nested document comments. Simply document schema looks like this:
{
"_id" : ObjectId("5867e5e64f768509c59f9392"),
"userId" : 1,
"comments": [
{
"id" : 1,
"text": "a"
},
{
"id" : 2,
"text": "b"
}
]
}
I want to project only the requested comment. I found an acceptable solution. (Only comment object return solutions are also welcome)
> db.posts.find({userId: 1, 'comments.id': 1}, {'comments.$': 1});
{ "_id" : ObjectId("5867e5e64f768509c59f9392"), "comments" : [ { "id" : 1, "text" : "a" } ] }
Then I try to apply it to mongodb repository interface with query annotation.
@Query(
value = ""
+ "{"
+ " 'userId' : '?1',"
+ " 'comments.id': '?2',"
+ "}",
fields = "'comments.$'"
)
Note findComment(String userId, String commentId);
But i got cast exception. Is there a better way to do this with spring-data-mongodb?
Upvotes: 1
Views: 1260
Reputation: 75914
Your @Query json is ill formed.
Try this.
@Query( value="{ 'userId' : ?0 , 'comments.id': ?1 }", fields = "{ 'comments.$' : 1}")
Upvotes: 1