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

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

如何使用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();
mongodb spring-data-mongodb
1个回答
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);
    }

这非常有效。

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