查找不同的嵌入式文档,并使用字段进一步使其与众不同

问题描述 投票:1回答:1

我正在使用Spring Boot Mongo示例。我经历了很多链接,例如:I want result with distinct value of one field from mongodb using spring data,但仍然没有突破。我正在使用以下代码:

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

使用此代码,我得到了重复的HealthCode=E,如果我可以对healthCd字段做出决定,是否可以采取任何方法?注意:Healths是患者文档中的嵌入式文档。

响应:

[
  {
    "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"
  }
]
spring mongodb spring-data-mongodb
1个回答
0
投票

您可以使用MongoBD聚合获得所需的结果(取look:]

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

MongoPlayground

© www.soinside.com 2019 - 2024. All rights reserved.