0

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

4
  • What did you try so far? What is your specific question/problem? Commented Aug 11, 2015 at 12:16
  • I know how to query if i know the key. But in this case, i dont know what keys to expect and the keys are in a nested document: Fruits Commented Aug 11, 2015 at 12:20
  • possible duplicate of MongoDB extracting values from BasicDBObject (Java) Commented Aug 11, 2015 at 12:44
  • Probably my question is not understood properly. (1) I just want to access the inner document which is under "Fruits" (2) I want to iterate over all the keys in that document since i dont know what keys are present inside it Commented Aug 11, 2015 at 16:40

1 Answer 1

0

The easiest way that you can do:

    Map<String, Integer> map = (Map) document.get("Fruits");
    Iterator iterator = map.keySet().iterator();
    String inventory = " ";
    while(iterator.hasNext()) {
        String key = iterator.next().toString();
        int value = map.get(key);
        inventory += value + " " + key;
        if (iterator.hasNext()) {
            inventory += ", ";
        } else {
            inventory += ".";
        }
    }

This should be work but casting is not recommended thing, so better check this link and figure out how to avoid it with BsonReader:
http://mongodb.github.io/mongo-java-driver/3.0/bson/readers-and-writers/

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.