I am new to MongoDB. My sample document is
{
\"Notification\" : [
{
\"date_from\" : ISODate(\"2013-07-08T18:30:00Z\"),
\"date
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));