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

尝试这个:

  DBCursor cursor = collection.find(new BasicDBObject("prices.type", "carpet"), new BasicDBObject("prices", 1)); try { while (cursor.hasNext()){ DBObject doc = cursor.next(); ArrayList prices= (ArrayList) 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(); } 

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