Java MongoDB访问对象子节点

时间:2012-10-11 20:18:12

标签: java mongodb

我将MongoDB中的以下文档提取到Java中:

{
    "_id": {
        "$oid": "5076371389d22e8906000000"
    },
    "item": {
        "values": [
            {
                "value1": [
                    4958,
                    3787,
                    344
                ],
                "value2": [
                    4,
                    13,
                    23
                ]
            }
        ], 
        "name": "item1"
    }
}

使用

M mongo = new M("database", "collection");
String query = "{\"item.name\":\"item1\"}";
DBCursor cur = mongo.collection.find(mongo.query(query));
while(cur.hasNext()) {
    System.out.println(cur.next().toString());
    // I need to access value1 array. 
}

我需要访问value1数组,我还需要拉整个文档,所以我不能只是让Mongo为我返回这个。就像我拉这个文件一样,需要做一个计算并再次使用该文件。 我理解这个结果可以转换成地图。但是,由于它是一个多维度的对象,我将如何能够浏览它。感谢

1 个答案:

答案 0 :(得分:2)

试试这个:

  //try catch omitted
  Mongo mongo = new Mongo("localhost", 27017);
  DB db = mongo.getDB("db");

  BasicDBObject query = new BasicDBObject("item.name","item1");
  DBCursor cur = db.getCollection("items").find(query);
  while(cur.hasNext()) {
      BasicDBObject object = (BasicDBObject) cur.next();
      BasicDBObject item =  (BasicDBObject) object.get("item");
      BasicDBList valueslist = (BasicDBList) item.get("values");
      BasicDBObject values = (BasicDBObject) valueslist.get(0);
      BasicDBList value1 = (BasicDBList) values.get("value1");
      System.out.println(value1); 
  }

你可以对它进行优化,但我希望你明白这一点并且有所帮助。 欢呼声