简体   繁体   中英

Query a document on array elements in MongoDB using Java

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

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);

It does not search for the document whose "url" is "www.adf.com" .

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");

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);

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

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM