Mongo Database save data from Map

Marc Stevens picture Marc Stevens · Jul 24, 2011 · Viewed 22.7k times · Source

I have the below code which works:

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

However I have the data for Department A and B in a map like:

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

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?

The data that goes into the map already is taken from the database like so:

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

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

Any ideas?

Thanks for any help or suggestions!

Answer

jtoberon picture jtoberon · Jul 25, 2011

Native Java types (int, float, String, Date, Map, etc) will get automatically encoded to the right BSON type, so you can use a BasicDBObject to put the Map straight into the mongo collection:

// 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));

However, it looks like your Map doesn't actually have the structure that you want, so you need some kind of mapping to the desired structure. Either use the basic mapping that's built into the java driver (you're on the right track by calling BasicDBObject.put, and here are some more ideas), or use something like Morphia for extended mapping.