Reputation: 371
I'm working on a Spring application and I'm using MongoDB as my database. I have a document structure where I am saving the id of another document to use as a reference. This id is an objectId and then save it using
mongoOperations.save(message)
It is using the same objectId as the one I'm saving for reference to create _id field for this newly created document. So my document is like this
{
"_id":{
"$oid":"610a03578c9e4937107b6501"
},
"ConversationId":{
"$oid":"610a03578c9e4937107b6501"
},
"Author":"author",
"Body":"hey there",
"CreatedAt":{
"$date":{
"$numberLong":"1628171556888"
}
}
}
As you can see that both the ids for _id and ConversationId are the same. I have tried saving ConversationId as a string and it still does the same. Not sure what mistake I'm making.
{
"_id":{
"$oid":"610a03578c9e4937107b6501"
},
"ConversationId": "610a03578c9e4937107b6501",
"Author":"author",
"Body":"hey there",
"CreatedAt":{
"$date":{
"$numberLong":"1628171556888"
}
}
}
This is my model class
@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 in the above model class id an objectId and I tried saving it as a string as mentioned above so It was set to type String here. I have also tried making it ObjectId and still the same issue persists.
How to make it create a unique _id for each record and not use conversationId as its id.
Upvotes: 0
Views: 1146
Reputation: 301
I think you need to change id to _id. Attaching reference below
@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;
}
Upvotes: 1