Mongo数据库从Map保存数据

时间:2011-07-24 19:41:35

标签: java mongodb map mongo-java

我的代码如下:

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

有什么想法吗?

感谢您提供任何帮助或建议!

3 个答案:

答案 0 :(得分:6)

原生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.put在正确的轨道上,而here是更多的想法),或者使用像Morphia这样的扩展映射。

答案 1 :(得分:3)

好的,我让它运转了。

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

就这么简单!

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

答案 2 :(得分: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中

相关问题