0

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?

1
  • What is your mongo server and spring mongo jar version ? Commented Feb 20, 2018 at 12:53

3 Answers 3

2

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")); 
Sign up to request clarification or add additional context in comments.

3 Comments

Your second proposition works better, I get this as a result: WriteResult{n=1, updateOfExisting=true, upsertedId=null}. But it still doesn't save anything in the database :/
Is "PersonEntity.class" an Enum(represent the ollection name)? Are you sure it reflects the name and nut the numeric value?
I was missing a @qualifier for my mongoOperations so it was saving in the wrong database. So using Collections.singletonMap("label", "JAP") resolved my problem. Thank you very much! wasted too much time in this.
0

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

Comments

0

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.