Search code examples
javamongodbspring-dataspring-mongodb

How to delete elements from nested array of documents with spring mongo


I have the following type of document representing projects in Mongo DB :

{
    "_id" : "5f69c22b669f2d3b308ce2e2",
    "actions" : [ 
        {
            "_id" : "1",
            ...
        }, 
        {
            "_id" :"2",
            ...
        }, 
        {
            "_id" : "n",
            ...
        },
        ...
    ]
}

and I'd like to delete specified actions by their actionsIds for the project projectId.

I tried the code below :

mongoOperation.updateMulti(
    Query.query(Criteria.where("id").is(projectId)),
    new Update().pull("actions", Query.query(Criteria.where("id").in(actionIds))),
    Project.class
);

But it doesn't delete anything.

Could you help me please ?

Thank you


Solution

  • I've finally figured out how to do it :

    DBObject pullUpdate = BasicDBObjectBuilder.start().add(
          "id",
          BasicDBObjectBuilder.start().add("$in", actionIds).get()
    ).get();
    mongoOperation.updateMulti(
          Query.query(Criteria.where("id").is(projectId)),
          new Update().pull("actions", pullUpdate),
          Project.class
    );