How many documents were removed in MongoDB

mongodb, spring-data

Solution

When you write documents in MongoDB (including removing) you can call getLastError() to see what effect your last write operation had.

The problem you have is that when there is no error, you still want to know how many objects (documents) were affected by your operation.

In the shell you can see the details by examining the object returned by `getLastErrorObj()`. In Java the Mongo Java driver provides methods to do the equivalent.

In the case of a remove operation, the field `"n"` will correspond to the number of affected documents. Here's a small snippet of an example:

import com.mongodb.WriteResult;
...
   WriteResult wr = collection.remove(new BasicDBObject());  // removes everything
   System.out.println(wr.getN());        // prints the number of removed documents

Problem

Using Spring Data (1.1.0.M1) is there a way to determine how many documents were removed? Currently I'm using the `remove()` method on the `MongoTemplate` class, but it does not return any sort of information about the operation. If not through `MongoTemplate`, is there a different way to remove documents and also find out how many were removed?

Original source