使用 MongoTemplate 和 Query API 从可用数组对象列表中仅获取匹配的数组对象
Fetch only matched array object from a list of available array objects with MongoTemplate and Query API
我有一个场景,我将参数传递给 MongoDB 中的集合,并仅获取符合我的条件 的特定数组对象 serviceType ]"serviceType"= 维修和修复。
集合样本
"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);
}
如何使用 mongotemplate 和 Query api of Spring boot Mongo 来处理这种情况?
你只需要替换这一行
query.fields().include("serviceTypes.serviceType");
用下面一行
query.fields().include("serviceTypes").position("serviceTypes",1);
我有一个场景,我将参数传递给 MongoDB 中的集合,并仅获取符合我的条件 的特定数组对象 serviceType ]"serviceType"= 维修和修复。
集合样本
"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);
}
如何使用 mongotemplate 和 Query api of Spring boot Mongo 来处理这种情况?
你只需要替换这一行
query.fields().include("serviceTypes.serviceType");
用下面一行
query.fields().include("serviceTypes").position("serviceTypes",1);