如何使用Java驱动程序访问MongoDB中嵌套在数组中的对象 [英] How to access object nested inside an array in MongoDB using Java driver

查看:90
本文介绍了如何使用Java驱动程序访问MongoDB中嵌套在数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{ "_id" : 0 , 
  "prices" : [ 
      { "type" : "house" , "price" :     10345} , 
      { "type" : "bed" , "price" : 456.94} , 
      { "type" : "carpet" , "price" : 900.45} , 
      { "type" : "carpet" , "price" : 704.48}
   ]
}

在avobe文档中如何我会用java驱动程序删除价格最低的地毯吗?即,我要删除 {type:carpet,price:704.48}

In avobe document how'll I delete the carpet which have lowest price using java driver? i.e., I've to delete { "type" : "carpet" , "price" : 704.48}

推荐答案

试试这个:

   DBCursor cursor = collection.find(new BasicDBObject("prices.type", "carpet"),
                new BasicDBObject("prices", 1));

            try {
                while (cursor.hasNext()){
                    DBObject doc = cursor.next();

                    ArrayList<BasicDBObject> prices= (ArrayList<BasicDBObject>) doc.get("prices");

                    double minPrice = -1;

                    for(BasicDBObject dbObject: prices){
                        if (!dbObject.get("type").equals("carpet"))
                            continue;

                        double price= (Double) dbObject.get("price");

                        if (minPrice == -1) {
                            minPrice = price;
                            continue;
                        }

                        if (price< minPrice )
                            minPrice = price;
                    }

                    for (BasicDBObject dbObject: prices){
                        if (dbObject.get("type").equals("carpet") && (((Double) dbObject.get("price")) == minPrice)){
                            collection.update(new BasicDBObject("_id", doc.get("_id")),
                                    new BasicDBObject("$pullAll", new BasicDBObject("prices", Arrays.asList(dbObject))));
                            System.out.println(dbObject);
                        }
                    }
                }
            } finally {
                cursor.close();
            }

我的解决方案可能不是很好))但我想告诉你一个替代品变体

My solution can be not very well )) but I wanted show you an alternate variant

这篇关于如何使用Java驱动程序访问MongoDB中嵌套在数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆