我是MongoDB的新手,在这里有点疯狂。我正在使用最新的mongo驱动程序版本和下拉向导。
我使用POJO来编写DDBB,它可以工作。但是,在尝试获取元素时,我没有得到实际的_id。以下是我尝试过的:
数据库文档
{
_id:603c249cbb33487d9baa49f8,
name:"John"
}Person类
public class Person {
@BsonProperty("_id")
@BsonId
private ObjectId id;
@NotNull
@JsonProperty
private String name;
}返回:
{
"id": {
"timestamp": 1614554268,
"counter": 11160056,
"machineIdentifier": 12268360,
"processIdentifier": 32155,
"timeSecond": 1614554268,
"time": 1614554268000,
"date": 1614554268000
},
"name": "John"
}如您所见,它不返回实际的_id (如603c249cbb33487d9baa49f8)。我试过将id设置为字符串,但我得到了错误Failed to decode 'Person'. Decoding '_id' errored with: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is OBJECT_ID.
我跟随了几个向导,我在这里搜索了一些问题,但似乎没有任何效果。
任何帮助都是非常感谢的!
发布于 2021-03-23 11:06:26
您不需要使用@BsonId,您可以简单地使用@Id和id字段的data-type应该是String。在本例中,您将获得由mongo生成的12bit Id。
public class Person {
@Id
private String id;
@NotNull
@JsonProperty
private String name;
}发布于 2021-09-08 06:00:27
您可以只使用@MongoId而不是@BsonId
public class Person {
@MongoId
private String id;
@NotNull
@JsonProperty
private String name;
}https://stackoverflow.com/questions/66415106
复制相似问题