Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to render a BasicDBObject into Map<String,String> with MongoDB/Java?

Tags:

java

mongodb

Is there a way to render a BasicDBObject into Map<String,String> with MongoDB/Java?

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;
}
like image 482
quarks Avatar asked Jan 19 '23 01:01

quarks


1 Answers

You can call toMap() function on BasicBSONObject which returns LinkedHashMap<String,Object>

like image 148
Nat Avatar answered Jan 20 '23 15:01

Nat