使用Java在MongoDB中查询数组元素的文档 [英] Query a document on array elements in MongoDB using Java

查看:818
本文介绍了使用Java在MongoDB中查询数组元素的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to MongoDB. My sample document is

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

我正在尝试更新其<$的通知c $ c>url:www.adf.com。我的Java代码是:

I am trying to update the Notification whose "url" : "www.adf.com". My Java code to do this is:

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

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

它不会搜索urlwww.adf.com

推荐答案

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

You have a nested document in this case. Your document has a field Notification which is an array storing multiple sub-objects with the field url. To search in a sub-field, you need to use the dot-syntax:

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

然而,这将返回整个文件的整个通知数组。您可能只想要子文档。要对此进行过滤,您需要使用 Collection.find的双参数版本

This will, however, return the whole document with the whole Notification array. You likely only want the sub-document. To filter this, you need to use 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);

。$ 表示只有此数组的第一个条目与find-operator匹配

The .$ means "only the first entry of this array which is matched by the find-operator"

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

This should still return one document with a sub-array Notifications, but this array should only contain the entry where url == "www.example.com".

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

To traverse this document with Java, do this:

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

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

By the way: When your database grows you will likely run into performance problems, unless you create an index to speed up this query:

con.coll.ensureIndex(new BasicDBObject("Notification.url", 1));

这篇关于使用Java在MongoDB中查询数组元素的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆