How to genearate "_id" : "01A63D2B-1724-456E-B2C0-3B3729951654" instead of "_id" : ObjectId("570602c46399e320c3022c6b")
My Student.class
@Entity("student")
public class Student {
@Id
private String Id;
private long studentId;
private String studentName;
private String qualification;
public Student(){
}
public Student(long studentId, String studentName, String qualification) {
this.studentId = studentId;
this.studentName = studentName;
this.qualification = qualification;
}
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
Function to add JSON Data to MOngoDB :
public void importFromJsonToMongoDB(File file) throws FileNotFoundException{
try{
String strJson = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
JSONArray jsonArr = new JSONArray(strJson);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
String str = jsonObj.toString();
ObjectMapper mapper = new ObjectMapper();
Student std = mapper.readValue(str, Student.class);
sr.save(std);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println("Error While parsing data");
}
* How to Auto Generate id? rather than MongoDb generating it.
Replace the existing NO-arg Constructor with following one in Student.class
public Student(){
super();
id = UUID.randomUUID().toString();
}
I think you need to add "_id" field while inserting the document in MongoDB. since you are not specifying any "_id" field it will automatically be generated by MongoDB. You can also use getNextSequence() method of mongodb to generate the id according to your preference.
Note: StudentID and _id are two different entities in the same document.
I hope these link will be useful for you: https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.