For a mongo database which has the following details:
[{
"Name" : "Krishna",
"Fruits" : {
"Apples" : 5,
"Oranges" : 10
}
},
{
"Name" : "Kiran",
"Fruits" : {
"Plums" : 10,
"Watermelons" : 1
}
}]
I want to print the following output:
Krishna has 5 Apples, 10 Oranges
Kiran has 10 Plums, 1 Watermelons
Following is the snippet of code I wrote. Please help me in filling up the blanks. Please note that there is no limit on the kind of fruits that the user can have.
try {
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection < Document > collection = database.getCollection("inventory");
MongoCursor < Document > cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
Document doc = cursor.next();
String name = doc.getString("Name"));
//TODO: Fill inventory
String inventory =
System.out.println(name + " has " + inventory);
}
} finally {
cursor.close();
}
} catch (MongoException e) {
e.printStackTrace();
}
Accept the solution proposed by Igor