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

3
  • Do you know the specific entry you want to delete (ie do you know the price) or are you trying to delete the minimum one no matter which price? Commented Jun 14, 2014 at 17:41
  • @Joachim Isaksson minimum one with type = carpet Commented Jun 14, 2014 at 17:46
  • Have you tried update with $pull: docs.mongodb.org/manual/reference/operator/update/pull ? Commented Jun 15, 2014 at 2:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.