使用 Spring 数据 Mongo 从文档中找到不同的嵌入文档?

find distinct embedded documents from the document using Spring Data Mongo?

如何使用 Spring 数据 Mongo 或 Mongo 模板或 Mongo 操作从嵌入文档中删除重复项?

如果我这样做

db.inventory.distinct( "hobbies" )

这给了我所有不同的爱好,但如果我喜欢下面的话,我就不会得到不同的记录。

示例文档:

{
  "_id" : ObjectId("592c7029aafef820f432c5f3"),
  "_class" : "lankydan.tutorial.mongodb.documents.Person",
  "firstName" : "John",
  "secondName" : "Doe",
  "dateOfBirth" : ISODate("2017-05-29T20:02:01.636+01:00"),
  "address" : [
      {
        "addressLineOne" : "19 Imaginary Road",
        "addressLineTwo" : "Imaginary Place",
        "city" : "Imaginary City",
        "country" : "US"
      },
      {
        "addressLineOne" : "22 South Road",
        "addressLineTwo" : "South Place",
        "city" : "CA",
        "country" : "US"
      }
    ],
  "profession" : "Winner",
  "salary" : 100,
  "hobbies" : [ 
    {
      "name" : "Badminton"
    }, 
    {
      "name" : "TV"
    }
  ]
}

{
  "_id" : ObjectId("592c7029aafef820f432c9h0"),
  "_class" : "lankydan.tutorial.mongodb.documents.Person",
  "firstName" : "Shrutika",
  "secondName" : "Parate",
  "dateOfBirth" : ISODate("2017-05-29T20:02:01.636+01:00"),
  "address" : [
      {
        "addressLineOne" : "20 Love Road",
        "addressLineTwo" : "Love Place",
        "city" : "Imaginary City",
        "country" : "US"
      },
      {
        "addressLineOne" : "22 North Road",
        "addressLineTwo" : "North Place",
        "city" : "LA",
        "country" : "UK"
      }
    ],
  "profession" : "Winner",
  "salary" : 100,
  "hobbies" : [ 
    {
      "name" : "Badminton"
    }, 
    {
      "name" : "TV"
    },
    {
      "name" : "Cricket"
    },
    {
      "name" : "Tenis"
    }
  ]
}

Spring数据Mongo查询:

@Query(value = "{}", fields = "{'hobbies' : 1}")
List<inventory> findByHobbiesDistinctName();

我使用最新版本的 Spring Boot Mongo 并使用 Spring 解决了这个问题Boot 库 v 2.1.4.RELEASE。

更多详情可参考这里:https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct

List<Object> object = mongoTemplate.query(Person.class).distinct("hobbies").all();
    for (Object object2 : object) {
        Hobbies hobbies = (Hobbies) object2;
        System.out.println(hobbies);
    }

这个效果很好。