java mongo 查询数组,使用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".

解决方案

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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值