仅使用“查询”或“协议”获取嵌入式文档效果不佳

时间:2019-04-04 11:43:30

标签: mongodb spring-data-mongodb

我的收藏夹中有多个地址,我想提取所有这些地址,该怎么办?我在下面尝试过,但是效果不佳。

Query query = new Query();
query.fields().include("Address");
List<Address> list1 = template.find(query, Address.class);
System.out.println(list1);

这是收藏集

{
  "_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"
    }
  ]
} 

下面的方法效果很好,但是我松散了UserAll的findAll()方法。如何填补这一空白?

@Query(value = "{}", fields = "{_id : 0, address:1}")
List<User> findAll();

1 个答案:

答案 0 :(得分:0)

您需要通过在_id中添加query fields运算符来从exclude中删除query

Query query = new Query();
query.fields().include("Address").exclude("_id");
List<Address> list1 = template.find(query, Address.class);

System.out.println(list1);

希望这可以解决您的问题。