Query a document on array elements in MongoDB using Java

后端 未结 1 826
不思量自难忘°
不思量自难忘° 2021-02-04 12:12

I am new to MongoDB. My sample document is

{
    \"Notification\" : [
        {
            \"date_from\" : ISODate(\"2013-07-08T18:30:00Z\"),
            \"date         


        
相关标签:
1条回答
  • 2021-02-04 13:02

    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));
    
    0 讨论(0)
提交回复
热议问题