如何使用Java驱动程序访问MongoDB中嵌套在数组中的对象

时间:2014-06-14 17:35:34

标签: java mongodb mongodb-java

{ "_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}

1 个答案:

答案 0 :(得分:1)

试试这个:

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

我的解决方案可能不太好))但我希望向您展示另一种变体