Query documents on array elements in mongodb using java

I'm 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"),"description" : "ddddddddddd","url" : "www.pqr.com"
        }
    ],

I'm trying to update the notification for "URL": "www.adf. Com" My java code does this:

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

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

It does not search for documents whose "URL" is "www.adf. Com"

Solution

In this case, you have a nested document Your document has a field notification, which is an array that stores multiple child objects with field URLs To search in subfields, you need to use point syntax:

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

However, this will return the entire document of the entire notification array You may only want this 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 a file and subarray notification, but the array should only contain entries with url = = "www.example. Com"

To traverse this document using Java:

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

By the way, as your database grows, you may encounter performance problems unless you create an index to speed up this query:

con.coll.ensureIndex(new BasicDBObject("Notification.url",1));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>