Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a document on array elements in MongoDB using Java

Tags:

java

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

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".

like image 865
Prashant Thorat Avatar asked Jul 26 '13 05:07

Prashant Thorat


1 Answers

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));
like image 85
Philipp Avatar answered Nov 10 '22 11:11

Philipp