据我所知,您想从MongoDB document
中获得每个字段。我假设您正在将 MongoDB document
传递给端点。
如果您有一个收集对象,并且要提取每个字段,则必须解析该对象,然后将进行进一步处理。所以我使用了**constructor injection**
和**JSON parsing**
。
另外,您忘记了在模型中声明habilidades
,但我已经在模型中声明了。
@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
}
@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();
}
}
我使用Simple JSON进行解析,并且按照您在问题中提到的方式解析了您的文档,并使用了构造函数注入,这是dependancy injection的一种。您也可以使用setter
或interface injection
。
您可以使用MongoRepsitory或MongoTemplate执行所有CRUD操作。另外,我建议使用MongoTemplate
以获得更好的执行效果。
,
根据您的集合示例,我假设您的所有属性均为“字符串”类型。为了分配给您的POJO,这是Java类。
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
//Other Imports
public class MyClass {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient();
//This registry is required for your Mongo document to POJO conversion
CodecRegistry codecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry);
MongoCollection<Empleado> collection = database.getCollection("mycoll",Empleado.class);
//This assigns your collection to your list of Java objects
List<Empleado> docs = collection.find(new Document(),Empleado.class).into(new ArrayList<Empleado>());
for(Empleado doc:docs) {
System.out.println("nombre="+doc.getNombre());
System.out.println("apellido="+doc.getApellido());
System.out.println("habilidades="+doc.getHabilidades());
//Display other attributes of your Mongodoc
}
mongoClient.close();
}
}
以下是示例输出:
nombre=Lalo
apellido=Tellez
habilidades=[Android,Tibco,Web]
本文链接:https://www.f2er.com/2351889.html