Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 查找不同的嵌入文档,并进一步使用字段进行区分_Spring_Mongodb_Spring Data Mongodb - Fatal编程技术网

Spring 查找不同的嵌入文档,并进一步使用字段进行区分

Spring 查找不同的嵌入文档,并进一步使用字段进行区分,spring,mongodb,spring-data-mongodb,Spring,Mongodb,Spring Data Mongodb,我使用的是Spring Boot Mongo示例。我浏览了很多链接,比如:,但仍然没有突破。我正在使用以下代码: List<Object> obj = mongoTemplate.query(Health.class).distinct("healths").all(); List<Health> healths = null; if (!CollectionUtils.isEmpty(obj)) { healths = obj.stream().map(e -&

我使用的是Spring Boot Mongo示例。我浏览了很多链接,比如:,但仍然没有突破。我正在使用以下代码:

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());
}
健康

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

    @Field
    private String healthCd;

    @Field
    private String healthName;

    @Field
    private LocalDateTime effDate;
}

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

Spring引导实现
package com.example.demo;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.boot.CommandLineRunner;
导入org.springframework.boot.SpringApplication;
导入org.springframework.boot.autoconfigure.springboot应用程序;
导入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;
@SpringBoot应用程序
公共类DemoApplication实现CommandLineRunner{
@自动连线
私有MongoTemplate MongoTemplate;
公共静态void main(字符串[]args){
run(DemoApplication.class,args);
}
@凌驾
公共无效运行(字符串…参数)引发异常{
////如果聚合中没有运算符或查询太复杂,
////使用下面的代码将MongoDB shell代码直接作为JSON编写
//新的聚合操作(){
//
//@覆盖
//公共文档到文档(聚合操作上下文){
//返回新文档(“$group”,
//新文档(“\u id”,“$healths.healthCd”)
//。附加(“healths”,新文件(“$first”,“$healths”));
//          }
//          
//      },
聚合agg=Aggregation.newAggregation(
聚合.sort(Direction.ASC,“healths.effDate”),
聚合集团(“healths.healthCd”)。第一(“healths”)。作为(“healths”),
聚合.replaceRoot(“健康”)
);
AggregationResults healths=mongoTemplate.aggregate(agg,
getCollectionName(Health.class)、Healths.class);
for(Healths-health:Healths.getMappedResults()){
Gson Gson=new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(health));
}
}
}

您可以发布示例输入数据吗。使用
MongoDB聚合
可以做比
.distinct()更多的事情
method@PAA您的spring boot版本是什么?@PAA请再次检查我的答案,确保您正在执行
mongoTemplate.aggregate
@PAA但是
mongoTemplate.query(Health.class).distinct(“healths”)
如何工作?您没有
healths
字段
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Health {

    @Field
    private String healthCd;

    @Field
    private String healthName;

    @Field
    private LocalDateTime effDate;
}
db.health.aggregate([
  {
    $sort: {
      "healths.effDate": 1
    }
  },
  {
    $group: {
      _id: "$healths.healthCd",
      healths: {
        $first: "$healths"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$healths"
    }
  }
])
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));
        }
    }
}