使用Java在MongoDB中查询关于数组元素的文档

Pra*_*rat 10 java mongodb

我是MongoDB的新手.我的示例文档是

{
    "Notification" : [
        {
            "date_from" : ISODate("2013-07-08T18:30:00Z"),
            "date_too" : ISODate("2013-07-30T18:30:00Z"),
            "description" : "fdfd",
            "url" : "www.adf.com"
        },
        {
            "date_from" : ISODate("2013-07-01T18:30:00Z"),
            "date_too" : ISODate("2013-07-30T18:30:00Z"),
            "description" : "ddddddddddd",
            "url" : "www.pqr.com"
        }
    ],
Run Code Online (Sandbox Code Playgroud)

我正在尝试更新其通知"url" : "www.adf.com".我的Java代码是:

BasicDBObject query=new BasicDBObject("url","www.adf.com");

DBCursor f = con.coll.find(query);
Run Code Online (Sandbox Code Playgroud)

它不会搜索其文件"url""www.adf.com".

Phi*_*ipp 13

在这种情况下,您有一个嵌套文档.您的文档有一个字段Notification,该字段是一个存储具有该字段的多个子对象的数组url.要在子字段中搜索,您需要使用点语法:

BasicDBObject query=new BasicDBObject("Notification.url","www.adf.com");
Run Code Online (Sandbox Code Playgroud)

但是,这将使整个文档返回整个文档Notification.您可能只想要子文档.要对此进行过滤,您需要使用Collection.find的双参数版本.

BasicDBObject query=new BasicDBObject("Notification.url","www.example.com");
BasicDBObject fields=new BasicDBObject("Notification.$", 1);

DBCursor f = con.coll.find(query, fields);
Run Code Online (Sandbox Code Playgroud)

.$装置"这是由find-操作者匹配这个阵列的仅第一条目"

这应该仍然返回一个带有子数组的文档Notifications,但是这个数组应该只包含其中的条目url == "www.example.com".

要使用Java遍历此文档,请执行以下操作:

BasicDBList notifications = (BasicDBList) f.next().get("Notification"); 
BasicDBObject notification = (BasicDBObject) notifications.get(0);
String url = notification.get("url");
Run Code Online (Sandbox Code Playgroud)

顺便说一句:当您的数据库增长时,您可能会遇到性能问题,除非您创建索引来加速此查询:

con.coll.ensureIndex(new BasicDBObject("Notification.url", 1));
Run Code Online (Sandbox Code Playgroud)