How to access object nested inside an array in Mon

2019-05-31 02:43发布

{ "_id" : 0 , 
  "prices" : [ 
      { "type" : "house" , "price" :     10345} , 
      { "type" : "bed" , "price" : 456.94} , 
      { "type" : "carpet" , "price" : 900.45} , 
      { "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}

1条回答
倾城 Initia
2楼-- · 2019-05-31 03:14

Try this:

   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

查看更多
登录 后发表回答