如何使用Java驱动程序

如何使用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}

最佳答案

尝试这个:

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


我的解决方案可能不太好)),但我想向您展示一个替代的变体

10-07 21:07