英文:
Fetch only matched array object from a list of available array objects with MongoTemplate and Query API
问题
I can help you with the translation. Here's the translated content:
有一个情况,我将参数传递给MongoDB中的一个集合,并仅获取与我的条件匹配的特定数组对象"serviceType"= Repairs & Fixes。
集合示例
"serviceTypes": [
{
"serviceType": "Installation/Uninstallation Service",
},
{
"serviceType": "Repairs & Fixes",
},
{
"serviceType": "Electricity Breakdown",
},
{
"serviceType": "Electricity Wiring",
}
]
根据我的实现,它获取所有数组对象,而不是特定的数组对象。上面的集合示例是以下代码的实际响应。
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);
}
如何使用Spring Boot Mongo的mongoTemplate和Query API处理此情况?
英文:
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?
答案1
得分: 1
只需将这一行替换为以下行:
query.fields().include("serviceTypes").position("serviceTypes",1);
英文:
You just need to replace this line
query.fields().include("serviceTypes.serviceType");
with the below line
query.fields().include("serviceTypes").position("serviceTypes",1);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论