Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

java - How to Get Only Matched Result from An Array Field of Document in Mongo Using Spring Data

I am using spring boot 1.5.1 and MongoDB version 3.4.6 .

I have a mongo document Hotel which has a list of Review .

The Review class has property userName.

@Document
public class Hotel {

    @Id
    private String id;
    private List<Review> reviews;

I want to search all the hotel by Review userName.

My HotelRepository has public List<Hotel> findByReviewsUserName(String userName);

When I am calling with user 'Salman' -

List<Hotel> list = this.hotelRepository.findByReviewsUserName(user);

this method returns result like below :

[
    {
        "id": "59b23c39c70ff63135f76b14",
        "name": "Signature",
        "reviews": [
            {
                "id": 1,
                "userName": "Salman",
                "rating": 8,
                "approved": true
            },
            {
                "id": 2,
                "userName": "Shahrukh",
                "rating": 5,
                "approved": false
            }
        ]
    }
]

What I want the reviews only of 'Salman' but it's also returning for others also.

What am I missing or how to do it?

What I have noticed is that if a single review user matched it returns the whole list of reviews which I don't want, I want reviews I have searched by name.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Great answer from @barbakini, but that also can be done without creating custom repository implementation with Criteria, just 'describe' which fields you would like to get, where 0 - .exclude, 1 - .include(

@Query(fields = "{ '_id': 0, 'reviews.$': 1 }")
List<Hotel> findByReviewsUserName(String userName);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...