简体   繁体   中英

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. I have the following request to 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:

{
    "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)?

You can use MongoOperations, AggregationOperation and Aggregation to search on in array as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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