查找不同的嵌入文档并使用 Field 进一步区分 [英] Find Distinct Embedded Document and further make distinct using Field

查看:28
本文介绍了查找不同的嵌入文档并使用 Field 进一步区分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring Boot Mongo 示例.我浏览了许多链接,例如:我想要使用 spring 数据从 mongodb 中获得一个字段的不同值的结果,但仍然没有得到任何突破.我正在使用以下代码:

Listobj = mongoTemplate.query(Health.class).distinct("healths").all();列表<健康>健康 = 空;if (!CollectionUtils.isEmpty(obj)) {healths = obj.stream().map(e -> (Health) e).collect(Collectors.toList());}

使用此代码,我得到了重复的 HealthCode=E,如果我可以对 healthCd 字段做出决定,有什么办法吗?注意:healths 是嵌入在 Patient 文档中的文档.

回复:

<预><代码>[{"healthCd": "D","healthName": "ABC",有效日期":2012-08-24T07:16:33"},{"healthCd": "C","healthName": "单声道",有效日期":2012-08-24T07:16:33"},{"healthCd": "E","healthName": "BONO",生效日期":2012-08-24T07:16:33"},{"healthCd": "B","healthName": "JOJO",有效日期":2012-08-24T07:16:33"},{"healthCd": "A","healthName": "KOKO",有效日期":2012-08-24T07:16:33"},{"healthCd": "1","healthName": "露露",有效日期":2012-08-24T07:16:33"},{"healthCd": "E","healthName": "BOBO",有效日期":2014-07-26T22:37:49"}]

健康

@Data@Builder@NoArgsConstructor@AllArgsConstructor公共课健康{@场地私人字符串 healthCd;@场地私人字符串健康名称;@场地私人 LocalDateTime effDate;}

解决方案

您可以使用 MongoBD 聚合来获得所需的结果(以 ):

db.health.aggregate([{$排序:{healths.effDate":1}},{$组:{_id: "$healths.healthCd",健康:{$first: "$healths"}}},{$替换根:{newRoot: "$healths"}}])

MongoPlayground

Spring Boot 实现

package com.example.demo;导入 org.springframework.beans.factory.annotation.Autowired;导入 org.springframework.boot.CommandLineRunner;导入 org.springframework.boot.SpringApplication;导入 org.springframework.boot.autoconfigure.SpringBootApplication;导入 org.springframework.data.domain.Sort.Direction;导入 org.springframework.data.mongodb.core.MongoTemplate;导入 org.springframework.data.mongodb.core.aggregation.Aggregation;导入 org.springframework.data.mongodb.core.aggregation.AggregationResults;导入 com.google.gson.Gson;导入 com.google.gson.GsonBuilder;@SpringBootApplication公共类 DemoApplication 实现 CommandLineRunner {@自动连线私人 MongoTemplate mongoTemplate;公共静态无效主(字符串 [] args){SpringApplication.run(DemoApplication.class, args);}@覆盖public void run(String... args) 抛出异常 {////如果你的操作符在聚合内部不可用或者查询太复杂,////使用下面的代码直接将MongoDB shell代码写成JSON//新的聚合操作() {////@覆盖//公共文档 toDocument(AggregationOperationContext context) {//返回新文档("$group",//新文档("_id", "$healths.healthCd")//.append("healths", new Document("$first", "$healths")));//}////},聚合 agg = Aggregation.newAggregation(Aggregation.sort(Direction.ASC, "healths.effDate"),Aggregation.group("healths.healthCd").first("healths").as("healths"),Aggregation.replaceRoot("healths"));AggregationResults<Healths>健康 = mongoTemplate.aggregate(agg,mongoTemplate.getCollectionName(Health.class), Healths.class);对于(健康状况:healths.getMappedResults()){Gson gson = new GsonBuilder().setPrettyPrinting().create();System.out.println(gson.toJson(health));}}}

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

解决方案

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

这篇关于查找不同的嵌入文档并使用 Field 进一步区分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆