How to convert MongoDB collection to Java object?

I am just starting out in the NoSQL (MongoDB) world and I am having a crash trying to convert my data collection to java objects for processing individually.

This is my collection that I get from mongo

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

I have already made the connection to mongoDB and these would be the objects to which I would like to assign, with their respective Getters and Setter.

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

I have not been able to advance because I cannot find a way to consume the mongo and assign each field to each object in java.
Thank you

Upvotes: 1

Views: 11075

Answers (2)

RLD
RLD

Reputation: 2005

As per your collection sample, I have assumed all your attributes 'String' type. For assigning to your POJO, here is the Java class.

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();
}
}

Here is sample output:

nombre=Lalo
apellido=Tellez
habilidades=[Android, Tibco, Web]

Upvotes: 1

Deep Dalsania
Deep Dalsania

Reputation: 453

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.

Upvotes: 0

Related Questions