找不到能够从类型 org.bson.types.ObjectId 转换为类型 int 的转换器(帮助)

No converter found capable of converting from type org.bson.types.ObjectId to type int (help)

我正在使用 Spring 数据和 mongodb 使用此函数获取所有测试数据:

当我运行这个

        List<Test> tests = mongoOps.findAll(Test.class);
    for(Test test : tests){
        log.info(test.toString());
    }

我的文档:

{ 
"_id" : ObjectId("56a09fd614923217ac1c545f"), 
"id" : 1.0, 
"address" : [
    1.0, 
    2.0, 
    3.0
]

}

我的测试class

@Document(collection = Test.COLLECTION_NAME)

public class 测试 {

public static final String COLLECTION_NAME = "test";

@Id
private int id;
private List<Double> address;

public Test(int id, List<Double> address) {
    super();
    this.id = id;
    this.address = address;
}

}

错误:

No converter found capable of converting from type org.bson.types.ObjectId to type int

如何解决?

您的id 属性 不是数据库中文档的标识符。 _id 是。您应该可以通过将域 class 调整为:

来阅读此内容
 class Test {

   @Id ObjectId databaseId;
   int id;
   …
 }

@Id 引用文档标识符,在您的情况下是 ObjectId。在 Spring Data MongoDB reference documentation

中阅读更多相关信息