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

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

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

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

I want to calculate distance between tallinn to other cities and beijing to other cities its continue to entire document

this is my java code

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

output

 2 -9 -26

I expect this type of output

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

1 Answer 1

3

First you should find out all distinct cityname and find all JAN of given city then iterate over all data and subtract the value.

Check below code :

 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();
   }
 }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.