I have a mongo DB query which returns 10000+ records. To the business service I want to return the records in GSON (google JSON) format. Following is the code snippet.
String mongoClientURI = null;
mongoClientURI = "mongodb://" + dbUser + ":" + pwd + "@" + host + ":" + port + "/" + databaseName;
MongoClient client = new MongoClient(new MongoClientURI(mongoClientURI));
MongoDatabase db = client.getDatabase(databaseName);
// Find query returns more than 10K records
FindIterable<Document> dbResult = db.getCollection("mycollection").find();
// This line takes too much time & CPU
List<Document> result = getDocumentArray(dbResult);
// This line takes too much time & CPU
JsonArray finalResult = getJSONArray(result);
public static List<Document> getDocumentArray(FindIterable<Document> input) {
List<Document> output = new ArrayList<Document>();
for (Document doc : input) {
output.add(doc);
}
return output;
}
public static JsonArray getJSONArray(Iterable<Document> docs) {
JsonArray result = new JsonArray();
if (docs == null) {
return result;
}
for (Document doc : docs) {
JsonObject jsonObject;
JsonParser parser = new JsonParser();
try {
jsonObject = parser.parse(doc.toJson()).getAsJsonObject();
result.add(jsonObject);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
return result;
}
Problem is it takes lot of time and CPU cycles while fetching and doing convesion of data from MongoDB to GSON array. Can anybody please tell me what is the effective way to fetch large dataset from mongodb into gson format?
Generally I get around 10k to 20K records, (50K max). I need to return all of them. My UI component requires all the records in one go to render the data. Generally people use data grid with paging, hence it does not have too many records in one go but in my case I have map component which takes all the records & creates a cluster of objects on the fly.
Any help would be much appreciated.
Atul Sureka