我有以下有效的代码:

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

但是我在地图中有部门A和部门B的数据,例如:
Map<Object,Object> map = new HashMap<Object,Object>();
map.put("1", "Department A");
map.put("2", "Department B");

最好/最简单的方法是保存此数据?有没有办法将地图直接放入mongo DB?还是我必须遍历地图?

进入地图的数据已经从数据库中获取,如下所示:
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);

更好的是,我可以将DBCursor对象放回数据库中。

有任何想法吗?

感谢您的帮助或建议!

最佳答案

本机Java类型(intfloatStringDateMap,等)将自动编码为正确的BSON类型,因此您可以使用BasicDBObjectMap直接放入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));

但是,您的Map似乎实际上没有所需的结构,因此您需要某种映射到所需的结构。可以使用内置在Java驱动程序中的基本映射(通过调用BasicDBObject.puthere可以找到更多思路),也可以使用Morphia之类的扩展映射。

07-25 23:25
查看更多