11

我是 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"
        }
    ],

我正在尝试更新其"url" : "www.adf.com". 我执行此操作的 Java 代码是:

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

DBCursor f = con.coll.find(query);

它不搜索其为 的"url"文档"www.adf.com"

4

1 回答 1

14

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

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

但是,这将返回带有整个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);

意思是“只有这个数组的.$第一个被查找操作符匹配的条目”

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

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

BasicDBList notifications = (BasicDBList) f.next().get("Notification"); 
BasicDBObject notification = (BasicDBObject) notifications.get(0);
String url = notification.get("url");

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

con.coll.ensureIndex(new BasicDBObject("Notification.url", 1));
于 2013-07-26T10:43:47.627 回答