有没有办法使用MongoDB / Java将BasicDBObject渲染为Map <string,string>?</string,string>

时间:2011-12-12 17:01:00

标签: java mongodb

有没有办法使用MongoDB / Java将BasicDBObject呈现到Map<String,String>

public Map<String,String> getObjectByKeyValue(String dbname, String collname, String key, String value) {

    Map<String,String> result = new HashMap<String, String>();

    DB db = mongo.getDB(dbname);
    DBCollection coll = db.getCollection(collname);

    BasicDBObject query = new BasicDBObject();
    query.put(key, value);
    DBCursor cur = coll.find(query);
    while (cur.hasNext()){
        DBObject obj = (DBObject) cur.next(); // Correct, or use BasicDBObject?
        // How to get each pair stored in the object be pushed into a Map<String,String> ?
    }
    return result;
}

1 个答案:

答案 0 :(得分:8)

您可以在BasicBSONObject上调用toMap()函数,该函数返回LinkedHashMap<String,Object>