I'm using MongoDB with the Java driver.
I've written a query that finds the minimum year for each region in the data.
Full code:
public void minYearPerRegion() {
for (int i = 0; i < uniqueRegions.size(); i++) {
BasicDBObject query = new BasicDBObject("Region", uniqueRegions.get(i));
BasicDBObject field = new BasicDBObject("Year", 1)
.append("Region", 1)
.append("Population", 1);
cursor = coll.find(query,field).sort(new BasicDBObject("Year",1)).limit(1);
try {
List<DBObject> documents = new ArrayList<DBObject>();
for (DBObject dbObject : cursor) {
DBObject o = cursor.next();
documents.add(o);
}
System.out.println("Document contains: " + documents.size() + " document/s");
} finally {
cursor.close();
}//end finally
}//end for
}//end minYearPerRegion
I'm trying to store my findings as individual documents but the cursor seems to present it as object. I've tried to split the object doing the following:
List<DBObject> documents = new ArrayList<DBObject>();
for (DBObject dbObject : cursor) {
DBObject o = cursor.next();
documents.add(o);
}
System.out.println("Document contains: " + documents.size() + " document/s");
However the print line always says the documents list only contains one documents when it should contain 4 (as there are 4 unique regions).
Please tell me how to get each document individually from the cursor and store it in an Array or List.