簡體   English   中英

MongoDB-Spring Data獲取僅包含請求字段的文檔(不多不少)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM