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

时间:2019-04-05 09:31:48

标签: mongodb spring-data-mongodb

如何使用Spring Data Mongo或MongoTemplate或MongoOperations从嵌入式文档中删除重复项?

如果我这样做

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 Data Mongo查询:

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

1 个答案:

答案 0 :(得分:0)

我能够使用最新版本的 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);
    }

这很好用。