将mongodb文档解析为字符串变量

时间:2013-12-05 06:07:46

标签: java mongodb

我是MongoDB的初学者。我试图用java api。我在mongodb中插入了很少的文档,我完成了使用java连接到mongo实例。

我的挑战是,我通过java进行mongodb查询得到一个文档。

结果是mongo中的一个文档,如下所示:

{ "_id" : { "$oid" : "528f13b5b55008f6487f7988"} , "NodeName" : "saurabhdeshpande" , "FirstName" : "saurabh" , "LastName" : "deshpande" }

我想将所有这些返回值转换为字符串变量,如

String nodename, String firstname, String lastname

请建议 - 我会这样做吗?

我尝试的代码是 -

    DBCursor cursor = coll.find();
        BasicDBObject query = new BasicDBObject("NodeName", name);

        cursor = coll.find(query);
        try {
            while (cursor.hasNext()) {

                System.out.println(cursor.next());
                DBObject tobj = cursor.next();
                details[0] = (String) tobj.get("NodeName");
                details[1] = (String) tobj.get("FirstName");
                details[2] = (String) tobj.get("LastName");

                System.out.println("in details ");
                for (int i = 0; i < details.length; i++) {
                    System.out.println("in details " + details[i]);
                }
            }
        } finally {
            cursor.close();
        }
        mongoClient.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:1)

你的结果将是一个BasicDBObject(基本上是一个Map),说result

String nodename = (String)result.get("NodeName");
String firstname = (String)result.get("FirstName");
String lastname= (String)result.get("LastName");

答案 1 :(得分:0)

你在同一个迭代中做了两个cursor.next(),这可能导致运行时异常。

DBCursor cursor = coll.find();
    BasicDBObject query = new BasicDBObject("NodeName", name);

    cursor = coll.find(query);
    try {
        while (cursor.hasNext()) {

            //System.out.println(cursor.next());
            DBObject tobj = cursor.next();
            System.out.println(tobj);
            details[0] = (String) tobj.get("NodeName");
            details[1] = (String) tobj.get("FirstName");
            details[2] = (String) tobj.get("LastName");

            System.out.println("in details ");
            for (int i = 0; i < details.length; i++) {
                System.out.println("in details " + details[i]);
            }
        }
    } finally {
        cursor.close();
    }
    mongoClient.close();
} catch (UnknownHostException e) {
    e.printStackTrace();
}