1
votes

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.

2

2 Answers

1
votes

You can call toArray() which, intuitively, returns a List<DBObject>. You're getting one document back because you passed limit(1) to the cursor.

0
votes

I found the solution to my attempt. The problem was, the List documents was being emptied every time the for loop executed because of the line:

List<DBObject> documents = new ArrayList<DBObject>();

To solve this I simply removed the List from the for loop like so:

public void minYearPerRegion() {
List<DBObject> documents = new ArrayList<DBObject>(); //<<<<<<<<<<<<<<<<
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 {

        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