我是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"),"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”的文档.
解决方法
在这种情况下,您有一个嵌套文档.您的文档有一个字段通知,它是一个存储多个具有字段url的子对象的数组.要在子字段中搜索,您需要使用点语法:
- BasicDBObject query=new BasicDBObject("Notification.url","www.adf.com");
然而,这将返回整个通知数组的整个文档.你可能只想要这个子文档.要过滤这个,你需要使用the two-argument version of Collection.find.
- BasicDBObject query=new BasicDBObject("Notification.url","www.example.com");
- BasicDBObject fields=new BasicDBObject("Notification.$",1);
- DBCursor f = con.coll.find(query,fields);
The .$
means “only the first entry of this array which is matched by the find-operator”
这应该仍然返回一个文件与子数组通知,但这个数组应该只包含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));