I recently spent some time using the statement $pullthrough the Spring Data MongoOperations interface, so I thought it would be nice to share my findings if someone encounters a similar problem.
So here it is ...
I have 2 java POJOs, for example:
@Document
public class OutterObject{
private String id;
private String name;
private List<InnerDocument> innerDocs;
public class InnerDocument{
private String id;
private String name;
This is stored in the Mongo collection:
"_id" : "doc2",
"_class" : "OutterObject",
"name" : "doc2",
"innerDocs" : [{
"_id" : "innerDoc21",
"name" : "innerDoc21"
}, {
"_id" : "innerDoc22",
"name" : "innerDoc22"
}]
I am trying to use the $ pull operator to delete all objects inside the innerDoc collection named name = "innerDoc22".
I know how to do this using the mongo driver, for example:
List<String> ids =
Arrays.asList("innerDoc22");
BasicDBObject find = new BasicDBObject();
match.put("innerDocs.name",
BasicDBObjectBuilder.start("$in", ids).get());
BasicDBObject update = new BasicDBObject();
update.put(
"$pull",
BasicDBObjectBuilder.start("innerDocs",
BasicDBObjectBuilder.start("name", "innerDoc22").get()).get());
DBCollection col= mongoOperations.getDb().getCollection("outterObject");
col.update(find , update);
I am trying to do the same using the Spring MongoOperations interface. Here is my code using the MongoOperations interface:
List<String> ids = Arrays.asList("innerDoc22");
Query removeQuery = Query.query(Criteria.where("innerDocs.name").in(ids));
WriteResult wc = mongoOperations.upsert(
removeQuery,
new Update().pull("innerDocs.name", "innerDoc22"),
OutterObject.class);
System.out.println(wc.getLastError());
I do not get any errors on the call getLastError(), the update just does not run in the database.
, , , , MongoOperations.