gpt4 book ai didi

java - MongoDB - Spring Data 获取仅包含请求字段的文档(不多也不少)

转载 作者:可可西里 更新时间:2023-11-01 10:46:34 25 4
gpt4 key购买 nike

我将 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);

关于java - MongoDB - Spring Data 获取仅包含请求字段的文档(不多也不少),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50604518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com