简体   繁体   English

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

[英]MongoDB - Spring Data fetch documents containing only requested fields(no more no less)

I am using MongoDB with Spring Boot 2.0 and Spring Data. 我将MongoDB与Spring Boot 2.0和Spring Data结合使用。 I have the following request to MongoDB 我对MongoDB有以下要求

{
    "cra": "test-cra",
    "service": "test-service",
    "timestamp": "2012-04-23T18:25:43.511Z",
    "parameters": [
         {
            "name": "test-param-name1",
            "value": "test-param-value1"
         }
    ]
}

In MongoDB, for example I have following documents: 例如,在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"
         }
    ]
}

In my response I want to see only one document that strictly respond to the request search parameters and it have to be: 在我的回复中,我只想看到一个严格响应请求搜索参数的文档,它必须是:

{
    "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"
             }
    ]
}

Can I, with the help of Spring Data, build the query for getting only documents that strictly respond to my request fields (not with more or less fields)? 我能否在Spring Data的帮助下构建查询以仅获取严格响应我的请求字段的文档(而不包含更多或更少的字段)?

You can use MongoOperations, AggregationOperation and Aggregation to search on in array as follows: 您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM