As far as I understand your question you want each field from your MongoDB document. I assumed that you are passing your MongoDB document to the endpoint.
If you have a collection object and you want to extract each field then you have to parse this object and you will process further. So I used **constructor injection** and **JSON parsing**.
Also, You forgot to declare habilidades in the model but I have declared in the model.
- This should be your model
@Document
public class Empleado {
private ObjectId _id;
private int numeroRegistro;
private String nombre;
private String apellido;
private int edad;
private int sueldo;
private List<String> habilidades;
public Empleado(ObjectId _id, int numeroRegistro, String nombre, String apellido, int edad, int sueldo,
List<String> habilidades) {
super();
this._id = _id;
this.numeroRegistro = numeroRegistro;
this.nombre = nombre;
this.apellido = apellido;
this.edad = edad;
this.sueldo = sueldo;
this.habilidades = habilidades;
}
// Getters and Setters
}
- This should be your controller.
@PostMapping("/insert")
public void insert(@RequestBody String doc) {
try {
JSONObject jsonObject = (JSONObject) new JSONParser().parse(doc);
JSONObject obj = (JSONObject) jsonObject.get("_id");
JSONArray array = (JSONArray) jsonObject.get("habilidades");
Empleado empleado = new Empleado((ObjectId) obj.get("$oid"),
Integer.parseInt(jsonObject.get("id").toString()), jsonObject.get("nombre").toString(),
jsonObject.get("apellido").toString(), Integer.parseInt(jsonObject.get("edad").toString()),
Integer.parseInt(jsonObject.get("sueldo").toString()), array);
// do something using getters and setters
} catch (Exception e) {
e.printStackTrace();
}
}
I used Simple JSON for parsing and I parsed your document as you mentioned in your question and I used constructor injection which is one type of dependancy injection. You can also use the setter or interface injection.
You can perform all CRUD operation either using MongoRepsitory or MongoTemplate. Also, I suggest that use MongoTemplate for better execution.