用于在mongo中打印嵌套文档中的键和值的Java代码

时间:2015-08-11 12:08:19

标签: java mongodb

对于具有以下详细信息的mongo数据库:

[{
    "Name" : "Krishna",
    "Fruits" : {
    "Apples" : 5,
    "Oranges" : 10
    }
},
{
    "Name" : "Kiran",
    "Fruits" : {
    "Plums" : 10,
    "Watermelons" : 1
    }
}]

我想打印以下输出:

Krishna has 5 Apples, 10 Oranges

Kiran has 10 Plums, 1 Watermelons

以下是我编写的代码片段。请帮我填补空白。请注意,用户可以拥有的水果种类没有限制。

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();
}

接受Igor提出的解决方案

1 个答案:

答案 0 :(得分:0)

您可以做的最简单的方法:

    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 += ".";
        }
    }

这应该是有效的,但不建议使用铸造,所以最好检查一下这个链接并找出如何用BsonReader避免它:
http://mongodb.github.io/mongo-java-driver/3.0/bson/readers-and-writers/