mongodb - java get字段值

时间:2015-06-01 08:29:45

标签: java mongodb mongodb-query

{ "_id" : 0, "cityname" : "tallinn", "JAN" : -3 }

{ "_id" : 1, "cityname" : "beijing", "JAN" : -5 }

{ "_id" : 2, "cityname" : "berlin", "JAN" : 12 }

{ "_id" : 3, "cityname" : "buenose", "JAN" : 23 }

我想计算塔林与其他城市之间的距离以及北京到其他城市的距离,它继续整个文件

这是我的java代码

try {
    BasicDBObject query = new BasicDBObject();
    BasicDBObject select = new BasicDBObject();
    select.put("JAN",1);
    select.put("_id",1);
    DBCursor cursor = coll.find(query,select);
    BasicDBObject obj = (BasicDBObject)cursor.next();
    int m,id;
    id=Integer.parseInt(obj.getString("_id"));
    for (int j=0;j<4;j++){
        m= Integer.parseInt(obj.getString("JAN"));
            if (id==j){
                while (cursor.hasNext()) {
                    int ma;
                    BasicDBObject object = (BasicDBObject)cursor.next();
                    ma= Integer.parseInt(object.getString("JAN"));
                    System.out.print((m-ma)+"  ");
                }
        }
    }
}
catch (MongoException e){
    System.out.println(e.getClass().getCanonicalName());
}

输出

 2 -9 -26

我期待这种类型的输出

0 2 -15 -26
-2 0 -17 -28
15 17 0 -11
26 28 11 0

1 个答案:

答案 0 :(得分:2)

首先,您应找出所有不同的cityname并查找给定JAN的所有city,然后迭代所有数据并减去该值。

检查以下代码:

 Mongo mongo = new Mongo("localhost", 27017);
 DB db = mongo.getDB("dbName");
 DBCollection collection = db.getCollection("collectionName");
 List distinctCity = collection.distinct("cityname");
 for(int i = 0; i < distinctCity.size(); i++) {
   BasicDBObject query = new BasicDBObject();
   query.put("cityname", distinctCity.get(i));
   BasicDBObject project = new BasicDBObject();
   project.put("JAN", 1);
   project.put("_id", 0);
   DBCursor cursorDoc = collection.find(query, project);
   while(cursorDoc.hasNext()) {
     BasicDBObject object = (BasicDBObject) cursorDoc.next();
     Integer currentValue = object.getInt("JAN");
     DBCursor allData = collection.find(new BasicDBObject(), project);
     while(allData.hasNext()) {
       BasicDBObject allDataObject = (BasicDBObject) allData.next();
       Integer allDataJanValue = allDataObject.getInt("JAN");
       Integer result = currentValue - allDataJanValue;
       System.out.print("  " + result + "  ");
     }
     System.out.println();
   }
 }
 }