Skip to content
Advertisement

How to query MongoDB with 2 conditions that has and relation

In my spring boot project, I am using MongoTemplate.

My mongo document is Hotel looks this:-

[
{
    "id": "601183876b7b976bd0a48b03",
    "name": "Club",
    "pricePerNight": 90,
    "address": {
        "city": "Espoo",
        "country": "Finland"
    },
    "reviews": [
        {
            "userName": "Masi",
            "rating": 9,
            "approved": true
        }
    ]
}
]

In my service class, I am trying to find as follows. My target is to find a hotel where the city name is an exact match and within a max price range. Following query don’t find anything. What is wrong?

    public List<Hotel> findRecommended(int maxPrice, String city){
    Query query = new Query()
                    .addCriteria(Criteria.where("city").is(city)
                    .andOperator(Criteria.where("pricePerNight").lte(maxPrice)))
                    .with(Sort.by(Sort.Order.desc("pricePerNight")))
                    .limit(4);

    List<Hotel> result = mongoTemplate.find(query, Hotel.class);
    return result;
}

Advertisement

Answer

city is part of address object

.addCriteria(Criteria.where("city")

should be

.addCriteria(Criteria.where("address.city")
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement