Mongo数据库从Map保存数据 [英] Mongo Database save data from Map

查看:204
本文介绍了Mongo数据库从Map保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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的数据,如: / p>

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

保存这些数据最好还是最简单的方法是什么?有没有办法将地图直接放入mongo DB?或者我必须遍历地图?

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

更好的是我可以把DBCursor对象重新放入数据库。

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

任何想法?

感谢任何帮助或建议!

推荐答案

int float String 日期 Map,等)将自动编码为正确的BSON类型,因此您可以使用 BasicDBObject Map 直接放入mongo集合中:

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

但是,它看起来像你的 Map 实际上你需要的结构,所以你需要某种映射到所需的结构。使用内置于java驱动程序中的基本映射(您通过调用 BasicDBObject.put 这里是一些更多的想法),或使用像Morphia这样的扩展映射。

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.

这篇关于Mongo数据库从Map保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆