春季启动mongodb不保存唯一id



我正在研究一个Spring应用程序,我使用MongoDB作为我的数据库。我有一个文档结构,我在其中保存另一个文档的id以用作引用。这个id是一个objectId然后用

保存它
mongoOperations.save(message)

它使用相同的objectId作为我保存的参考,为这个新创建的文档创建_id字段。所以我的文档是这样的

{
"_id":{
"$oid":"610a03578c9e4937107b6501"
},
"ConversationId":{
"$oid":"610a03578c9e4937107b6501"
},
"Author":"author",
"Body":"hey there",
"CreatedAt":{
"$date":{
"$numberLong":"1628171556888"
}
}
}

可以看到,_id和ConversationId的id是相同的。我试过将ConversationId保存为字符串,它仍然是一样的。我不知道我犯了什么错误。

{
"_id":{
"$oid":"610a03578c9e4937107b6501"
},
"ConversationId": "610a03578c9e4937107b6501",
"Author":"author",
"Body":"hey there",
"CreatedAt":{
"$date":{
"$numberLong":"1628171556888"
}
}
}

这是我的模型类

@Document(collection = "messages")
public class Message {
@Id
private String id;
@Field("ConversationId")
private String conversationId;
@Field("Author")
private String author;
@Field("Body")
private String body;
@Field("CreatedAt")
private Instant createdAt;
}

COnversationId在上面的模型类id一个objectId,我试图保存它作为一个字符串如上所述,所以它被设置为类型字符串在这里。我也试过使它成为ObjectId,但同样的问题仍然存在。

如何使它为每条记录创建一个唯一的_id,而不使用conversationId作为其id。

我认为你需要更改id_id. 附上参考

@Document(collection = "messages")
public class Message {

private String _id;
@Field("ConversationId")
private String conversationId;
@Field("Author")
private String author;
@Field("Body")
private String body;
@Field("CreatedAt")
private Instant createdAt;
}

最新更新