5

我有以下代码有效:

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 对象放回数据库中。

有任何想法吗?

感谢您的任何帮助或建议!

4

3 回答 3

9

本机 Java 类型(int, float, String,DateMap,)将自动编码为正确的 BSON 类型,因此您可以使用 aBasicDBObjectMap直接放入 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实际上并没有您想要的结构,因此您需要某种映射到所需结构。BasicDBObject.put要么使用内置在 java 驱动程序中的基本映射(通过调用,你在正确的轨道上,这里有更多的想法),或者使用像 Morphia 这样的东西进行扩展映射。

于 2011-07-25T03:25:36.220 回答
4

好的,伙计们,我得到了它的工作。

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

就如此容易!

感谢您的所有回复和建议!

于 2011-07-25T10:02:32.503 回答
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? Map可以通过构造函数本身直接添加到BasicDBObject中。这可以直接插入db而无需迭代。

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

DBCursor 实现了迭代器,所以不迭代就不能放回db

于 2011-07-25T03:26:20.483 回答