从mongoDB中的数组访问子文档

时间:2013-07-22 13:45:29

标签: java mongodb

这是我的sampale mongo doc。

"Notification" : [
        {
            "date_from" : ISODate("2013-06-30T18:30:00Z"),
            "date_too" : ISODate("2013-07-23T18:30:00Z"),
            "description" : "bbbbbbbbbbbbbbb",
            "url" : "bbbbbbbbbbbbbb"
        },
        {
            "date_from" : ISODate("2013-07-07T18:30:00Z"),
            "date_too" : ISODate("2013-07-16T18:30:00Z"),
            "description" : "ddd",
            "url" : "ddd"
        },
        {
            "date_from" : ISODate("2013-07-02T18:30:00Z"),
            "date_too" : ISODate("2013-07-29T18:30:00Z"),
            "description" : "cccc",
            "url" : "cccccccccccccc"
        }
    ],

我正在尝试访问“Notifications”:包含3个子文档的数组。我想单独检索每个文档。 我的java代码是

notification=(BasicDBList) f.curr().get("Notification");

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

BasicDBList扩展BasicBSONList,后者又扩展ArrayList。您可以使用索引从列表中获取单个元素。

BasicDBList notifications = (BasicDBList) cursor.curr().get("Notification");

BasicDBObject first = (BasicDBObject) notifications.get(0); //first document
BasicDBObject second = (BasicDBObject) notifications.get(1); //second document
BasicDBObject third = (BasicDBObject) notifications.get(2); //third document

System.out.println(first.get("description")); // bbbbbbbbbbbbbbb
System.out.println(second.get("url")); // bbbbbbbbbbbbbb

您可能希望迭代它们:

for(Object o : notifications) {
  BasicDBObject obj = (BasicDBObject) o;
  System.out.println(obj.get("url")); //prints the URL of every document in notifications
}