![](/img/trans.png)
[英]How do I disable mapping of fields for Spring Data MongoDB documents?
[英]MongoDB - Spring Data fetch documents containing only requested fields(no more no less)
我将MongoDB与Spring Boot 2.0和Spring Data结合使用。 我对MongoDB有以下要求
{
"cra": "test-cra",
"service": "test-service",
"timestamp": "2012-04-23T18:25:43.511Z",
"parameters": [
{
"name": "test-param-name1",
"value": "test-param-value1"
}
]
}
例如,在MongoDB中,我有以下文档:
{
"cra": "test-cra",
"service": "test-service",
"timestamp": "2012-04-23T18:25:43.511Z",
"body" : "<response><rating>0.5</rating></response>",
"parameters": [
{
"name": "test-param-name1",
"value": "test-param-value1"
},
{
"name": "test-param-name2",
"value": "test-param-value2"
}
]
}
{
"cra": "test-cra",
"service": "test-service",
"timestamp": "2012-04-23T18:25:43.511Z",
"body" : "<response><rating>0.5</rating></response>",
"parameters": [
{
"name": "test-param-name1",
"value": "test-param-value1"
}
]
}
在我的回复中,我只想看到一个严格响应请求搜索参数的文档,它必须是:
{
"cra": "test-cra",
"service": "test-service",
"timestamp": "2012-04-23T18:25:43.511Z",
"body" : "<response><rating>0.5</rating></response>",
"parameters": [
{
"name": "test-param-name1",
"value": "test-param-value1"
}
]
}
我能否在Spring Data的帮助下构建查询以仅获取严格响应我的请求字段的文档(而不包含更多或更少的字段)?
您可以使用MongoOperations,AggregationOperation和Aggregation在数组中进行搜索,如下所示:
ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
AggregationOperation match = Aggregation.match(Criteria.where("cra").is("test-cra"));
AggregationOperation unwind = Aggregation.unwind("parameters");
AggregationOperation match2 = Aggregation.match(Criteria.where("parameters.value1").is("test-param-value1"));
Aggregation aggregation = Aggregation.newAggregation(match, unwind, match2);
AggregationResults<AggregateFactoryResult> output = mongoOperation.aggregate(aggregation, "tablename", AggregateFactoryResult.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.