0

我将以下文档从 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 为我返回这个。就像我在拉这个文件一样,需要做一个计算并再次使用该文件。我了解此结果可以转换为地图。但是,由于它是一个多维对象,我将如何浏览它。谢谢

4

1 回答 1

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

你可以优化它,但我希望你明白这一点,它会有所帮助。干杯

于 2012-10-11T20:42:57.893 回答