I have a scenario where i pass a parameters to a collection in MongoDB and fetch only that particular array object serviceType which matched my criteria "serviceType"= Repairs & Fixes.
Collection Sample
"serviceTypes": [
{
"serviceType": "Installation/Uninstallation Service",
},
{
"serviceType": "Repairs & Fixes",
},
{
"serviceType": "Electricity Breakdown",
},
{
"serviceType": "Electricity Wiring",
}
]
As per my implementation below, it fetches all the array objects instead of that particular array object. The above collection sample is the actual response for the below code.
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
@Override
public ServiceList findOneByServiceType(String categoryName, String
serviceType1) {
// TODO Auto-generated method stub
Query query = new Query() ;
query.addCriteria(Criteria.where("categoryName").is(categoryName).andOperator(Criteria.where("serviceTypes").elemMatch(Criteria.where("serviceType").is(serviceType1))));
query.fields().include("serviceTypes.serviceType");
return (ServiceList) mongoTemplate.findOne(query,ServiceList.class);
}
How to handle this scenario with mongotemplate and Query api of Spring boot Mongo?