【问题标题】:How to convert MongoDB collection to Java object?如何将 MongoDB 集合转换为 Java 对象?
【发布时间】:2020-08-31 15:13:29
【问题描述】:

我刚开始使用 NoSQL (MongoDB) 世界,尝试将我的数据集合转换为 java 对象以进行单独处理时遇到了崩溃。

这是我从 mongo 获得的收藏

{
  "_id": {
    "$oid": "5ebda019508257a3e39e2331"
  },
  "id": "1",
  "nombre": "Lalo",
  "apellido": "Tellez",
  "edad": "18",
  "habilidades": [
    "Android",
    "Tibco",
    "Web"
  ],
  "sueldo": "20000"
}

我已经与 mongoDB 建立了连接,这些将是我想要分配的对象,它们各自具有 GettersSetter

public class Empleado {
    private ObjectId _id;
    private int numeroRegistro;
    private String nombre;
    private String apellido;
    private int edad;
    private int sueldo;
}

我无法前进,因为我找不到使用 mongo 并将每个字段分配给 java 中的每个对象的方法。
谢谢

【问题讨论】:

标签: java mongodb mongodb-java


【解决方案1】:

根据您的收藏示例,我假设您的所有属性都是“字符串”类型。为了分配给您的 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]

【讨论】:

    【解决方案2】:

    据我了解您的问题,您希望 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 的一种类型的构造函数注入。您也可以使用setterinterface injection
    您可以使用MongoRepsitoryMongoTemplate 执行所有CRUD 操作。另外,我建议使用MongoTemplate 以获得更好的执行效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-07
      • 2022-01-13
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多