Search code examples
javamongodbarraylistmongodb-java

Load an ArrayList of MongoDB documents into a Java class


So I want to load this ArrayList lineaCompra into my Java class. They got same atribbutes but I can't find a way to do it.

Here the document in Mongo:

{
    "_id" : ObjectId("5a15b007862b6815ac785e54"),
    "IDVenta" : 1,
    "IDCliente" : "12365456",
    "fechaCompra" : "22/11/2017",
    "lineaCompra" : [
            {
                    "idProducto" : "libro1",
                    "cantidad" : 2,
                    "precio" : 12
            },
            {
                    "idProducto" : "libro2",
                    "cantidad" : 2,
                    "precio" : 12
            }
    ]
}

My Java class

public class Compra {

    private String IDCliente; 
    private Date fechaCompra;
    private ArrayList<LineaCompra> Compras = new ArrayList<LineaCompra>();

}

The LineaCompra class (the one I ' load)

public class LineaCompra {

    private String titulo; //IDPRoducto
    private int cantidad;
    private float precio;

}

The code where I try to load it

BasicDBObject query = new BasicDBObject();
query.put("IDVenta", doc2.get("IDVenta"));  
//doc2 is all the document loaded,Should I put something else on 
//the query?
FindIterable<Document> cursor = collection.find(query); 
while (cursor.iterator().hasNext()) {
    DBObject theObj = ((Iterator<DBObject>) cursor).next(); 
    //Getting a exception here
    BasicDBList lineasList = (BasicDBList)theObj.get("lineaCompra");
    for (int j = 0; j < lineasList.size(); i++) {
        BasicDBObject lineasObj = (BasicDBObject)lineasList.get(j);
        aux2=new LineaCompra();
        aux2.setTitulo(lineasObj.getString("idProducto"));
        Double x=(Double) lineasObj.get("precio");
        aux2.setPrecio(x.floatValue());
        aux2.setCantidad(lineasObj.getInt("cantidad"));
        lineas.add(aux2);
    }               
}
aux.setCompras((ArrayList<LineaCompra>) lineas);
compras.add(aux);

Hope someone know how to do it. I have no idea. I have make some tests and I load all except that array. I have tries to cast it the result to ArrayList<LineaCompra> with no success.


Solution

  • Given the document in your question, the following code ...

    FindIterable<Document> cursor = collection.find(Filters.eq("IDVenta", 1));
    
    for (Document document : cursor) {
        // the lineaCompra attribute is an array of sub documents
        // so read it as a List and then iterate over that List
        // with each element in the List being a Document
        List<Document> lineaCompra = document.get("lineaCompra", List.class);
        for (Document d : lineaCompra) {
            System.out.println("idProducto: " + d.get("idProducto"));
            System.out.println("cantidad: " + d.get("cantidad"));
            System.out.println("precio: " + d.get("precio"));
            System.out.println("----");
        }
    }
    

    ... will print:

    idProducto: libro1
    cantidad: 2
    precio: 12
    ----
    idProducto: libro2
    cantidad: 2
    precio: 12
    ----
    

    This shows how to

    • Find by IDVenta
    • Extract the contents of the lineaCompra array of sub documents

    To create and populate an instance of LineaCompra for each of the documents in List<Document> lineaCompra you would do this:

    for (Document d : lineaCompra) {
        LineaCompra() aux2 = new LineaCompra();
        aux2.setTitulo(d.getString("idProducto"));
        aux2.setPrecio(d.getDouble("precio").floatValue());
        aux2.setCantidad(lineasObj.getInteger("cantidad"));
        lineas.add(aux2);
    }