0

If a function call is done in java like:

collection.update(match, new BasicDBObject("$pull", update));

How can I know the number of documents updated in database after this statement execution?

And my other problem is, that I want to remove an element from an array in a document, if that element exists the collection. How can I do that easily? Should I query to find whether it is present in collection and then delete it or is there any other easier way?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

0

1) The DBCollection.html#update method returns a WriteResult object that contains a n property, which contains the number of documents affected in the write operation.

2) I think there is no way to do that in a single operation. If, at insert moment, the element is already on array of other document, you could do an update to remove the element from array. Something like that:

DBObject newElement = ...

DBObject query = BasicDBObjectBuilder.start()
    .add("array", newElement)
    .get();

DBObject update = BasicDBObjectBuilder.start()
    .push("$pull")
        .add("array", newElement)
    .pop()
    .get(); 

collection.update(query, update);
collection.insert(newElement);
Miguel Cartagena
  • 2,576
  • 17
  • 20