Search code examples
springmongodbmongodb-queryspring-data-mongodb

How to remove elements from nested object array?


I'm trying to remove elements from nested object array. My document looks like this:

{
    "_id" : ObjectId("5a79b8a6b2ba9a49359fa3c3"),
    "_class" : "com.PersonEntity",
    "records" : [ 
        {
            "number" : "4905537",
            "label" : "ASH"
        }, 
        {
            "number" : "KM537",
            "label" : "JAP"
        }, 
        {
            "number" : "49537",
            "label" : "JAP"
        }
    ]
}

I want to delete all the records of all the documents where the record has the label "JAP".

This is the way I'm trying to do it:

Update update = new Update().pull("records", new BasicDBObject("label", "JAP"));
mongoOperations.updateMulti(new Query(), update, PersonEntity.class);

It seems that there is something wrong with this Update because removing is not working.

Can any body help me with this?


Solution

  • I belive you need to mention the name of the field, before the sub-field ("records.label" instead of "label").

    Try this one:

    Update update = new Update().pull("records", new 
                         BasicDBObject("records.label","JAP"));
    

    If this will not do, you may try:

    Update update = new Update().pull("records", 
                         Collections.singletonMap("label", "JAP"));