2014-06-14 19 views
1
{ "_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}如何使用Java驅動程序訪問在MongoDB中嵌套在數組中的對象

+0

你知道你想要的特定條目刪除(即你知道價格)還是你試圖刪除最低價格? –

+0

@Joachim Isaksson與'type = carpet'的最小值之一 – Towhid

+0

您是否試過用$ pull進行更新:http://docs.mongodb.org/manual/reference/operator/update/pull/? – TeTeT

回答

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

我的解決方案可能是不太好)),但我想告訴你一個替代變種

相關問題