0

这是我的样本 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"
        }
    ],

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

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

任何帮助表示赞赏。

4

1 回答 1

0

BasicDBListextends 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
}
于 2013-07-22T14:53:42.480 回答