Anna
Anna

Reputation: 889

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?

Upvotes: 0

Views: 2048

Answers (3)

Dila Gurung
Dila Gurung

Reputation: 1764

I also witness same issue but this is little different from accepted answer.

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

As you already mentioned records in key , so you need not write "records.label"

Upvotes: 0

Neel Rathod
Neel Rathod

Reputation: 2111

First you need to define a schema as const

const Chat = require('./modules/chat/chatModel')

and your query is like this:

    Chat.update({
            _id: ObjectId("5a79b8a6b2ba9a49359fa3c3"),
        }, {
            $pull: {
                records: {
                    label: "ASH"
                },
            },
        });

Upvotes: 0

AvrahamL
AvrahamL

Reputation: 201

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"));

Upvotes: 2

Related Questions