Find Distinct Embedded Document and further make distinct using Field

扶醉桌前 提交于 2021-02-07 10:34:43

问题


I'm using Spring Boot Mongo example. I went through many links like: I want result with distinct value of one field from mongodb using spring data, but still did not get any break through. I am using below code:

List<Object> obj = mongoTemplate.query(Health.class).distinct("healths").all();
List<Health> healths = null;
if (!CollectionUtils.isEmpty(obj)) {
    healths = obj.stream().map(e -> (Health) e).collect(Collectors.toList());
}

With this code I am getting duplicate HealthCode=E, Is there any way if I can take decision with the healthCd field ? Note: healths is embedded document within Patient document.

Response:

[
  {
    "healthCd": "D",
    "healthName": "ABC",
    "effDate": "2012-08-24T07:16:33"
  },
  {
    "healthCd": "C",
    "healthName": "MONO",
    "effDate": "2012-08-24T07:16:33"
  },
  {
    "healthCd": "E",
    "healthName": "BONO",
    "effDate": "2012-08-24T07:16:33"
  },
  {
    "healthCd": "B",
    "healthName": "JOJO",
    "effDate": "2012-08-24T07:16:33"
  },
  {
    "healthCd": "A",
    "healthName": "KOKO",
    "effDate": "2012-08-24T07:16:33"
  },
  {
    "healthCd": "1",
    "healthName": "LULU",
    "effDate": "2012-08-24T07:16:33"
  },
  {
    "healthCd": "E",
    "healthName": "BOBO",
    "effDate": "2014-07-26T22:37:49"
  }
]

Health

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Health {

    @Field
    private String healthCd;

    @Field
    private String healthName;

    @Field
    private LocalDateTime effDate;
}

回答1:


You may use MongoBD aggregation to get desired result (Take a look):

db.health.aggregate([
  {
    $sort: {
      "healths.effDate": 1
    }
  },
  {
    $group: {
      _id: "$healths.healthCd",
      healths: {
        $first: "$healths"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$healths"
    }
  }
])

MongoPlayground

Spring Boot Implementation

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    @Autowired
    private MongoTemplate mongoTemplate;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

//      //If your operator is not available inside Aggregation or query is too complex, 
//      //use below code to write MongoDB shell code directly as JSON
//      new AggregationOperation() {
//
//          @Override
//          public Document toDocument(AggregationOperationContext context) {
//              return new Document("$group", 
//                  new Document("_id", "$healths.healthCd")
//                      .append("healths", new Document("$first", "$healths")));
//          }
//          
//      },

        Aggregation agg = Aggregation.newAggregation(
            Aggregation.sort(Direction.ASC, "healths.effDate"),
            Aggregation.group("healths.healthCd").first("healths").as("healths"),           
            Aggregation.replaceRoot("healths")
        );

        AggregationResults<Healths> healths = mongoTemplate.aggregate(agg, 
                mongoTemplate.getCollectionName(Health.class), Healths.class);
        for (Healths health : healths.getMappedResults()) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(health));
        }
    }
}


来源:https://stackoverflow.com/questions/60009532/find-distinct-embedded-document-and-further-make-distinct-using-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!