2011-07-24 9 views
5

Tengo el siguiente código que funciona:Mongo Base de Datos de guardar los datos del mapa

if (aDBCursor.hasNext()) { 
    DBObject aDbObject = aDBCursor.next(); 
    aDbObject.put("title", "Test Title"); 
    ArrayList<DBObject> department = new ArrayList<DBObject>(); 

    DBObject nested1 = new BasicDBObject(); 
    nested1.put("name", "Department A"); 
    nested1.put("id", 1); 
    department.add(nested1); 

    DBObject nested2 = new BasicDBObject(); 
    nested2.put("name", "Department B"); 
    nested2.put("id", 2); 
    department.add(nested2); 

    aDbObject.put("department", department); 
    collection.save(aDbObject); 
} 

Sin embargo tengo los datos para el departamento A y B en un mapa como:

Map<Object,Object> map = new HashMap<Object,Object>(); 
map.put("1", "Department A"); 
map.put("2", "Department B"); 

¿Cómo sería la mejor/La forma más fácil de guardar estos datos? ¿Hay alguna manera de poner el mapa directamente en el mongo DB? ¿O tendría que recorrer el mapa?

Los datos que entra en el mapa ya está tomada de la base de datos de este modo:

String[] values = req.getParameterValues("departments"); 
Map<Object,Object> map = new HashMap<Object,Object>(); 

DBCollection collection = database.getCollection("Departments"); 
BasicDBObject query = new BasicDBObject(); 
query.put("id", new BasicDBObject("$in", values)); 
DBCursor cursor = collection.find(query); 

sería aún mejor es que sólo podía poner el dbcursor objeto de nuevo en la base de datos.

¿Alguna idea?

¡Gracias por cualquier ayuda o sugerencia!

Respuesta

5

tipos nativos Java (int, float, String, Date, Map, etc) conseguirán codificado automáticamente al tipo BSON derecha, por lo que puede utilizar un BasicDBObject para poner el Map directamente a la colección mongo:

// you probably want to be more specific with your generics than Object! 
Map<Object,Object> map = new HashMap<Object,Object>(); 
map.put("1", "Department A"); 
map.put("2", "Department B"); 
collection.insert(new BasicDBObject(map)); 

Sin embargo, parece que su Map en realidad no tiene la estructura que desea, por lo que necesita algún tipo de mapeo para la estructura deseada. Utilice el mapeo básico que está integrado en el controlador java (está en el camino correcto al llamar al BasicDBObject.put, y here son algunas ideas más), o utilice algo como Morphia para el mapeo extendido.

0

What would the best/easiest way be to save this data? Is there a way to put the map straight into the mongo DB? Or would I have to loop over the map? El mapa se puede agregar directamente a un BasicDBObject a través del propio constructor. Esto se puede insertar directamente en db sin necesidad de iterar.

Would be even better is I could just put the DBCursor object back into the database. 

dbcursor implementa iterador, por lo que no puede volver a poner en dB sin iterar

2

Ok chicos, yo tengo trabajo.

String[] values = req.getParameterValues("departments"); 
Map<Object,Object> map = new HashMap<Object,Object>(); 

DBCollection collection = database.getCollection("Departments"); 
BasicDBObject query = new BasicDBObject(); 
query.put("id", new BasicDBObject("$in", values)); 
DBCursor cursor = collection.find(query); 



if(aDBCursor.hasNext()){ 
     DBObject aDbObject=aDBCursor.next(); 
     aDbObject.put("title", "Test Title"); 
     aDbObject.put("department", cursor); 
     collection.save(aDbObject); 
    } 

Tan simple como eso!

¡Gracias por todas sus respuestas y sugerencias!

Cuestiones relacionadas