Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update and add to subdocument list with Spring+Mongo

I have a document like this in a MongoDB collection:

{
  id : ... 
  listA:[{
          id: ...,
          thing:...,
          listB:[{...},{...}]
          },...
            ]
}

(The top level ID is the normal auto-generated MongoDB ID. The other ID of the subdocument object is a pseudo-ID that I've generated separately and pushed into the list)

Questions: I would like to (1) add to listB and (2) change thing

This object can be pretty hefty and it is possible that more than one thread might be operating on the object so I want to avoid a findOne, update, then save type of scenario.

I'd like to do this in Spring Data in a similar way that I've done a push to listA, i.e.

@Autowired
private MongoOperations operations;

public void addStuff(String id, Stuff stuff) {
    operations.updateFirst(Query.query(Criteria.where("_id").is(id)),
            new Update().addToSet("listA", stuff), Stuffs.class);
}

However I'm having trouble generating the right Query/Criteria.

Thanks in advance.

like image 776
Manish Patel Avatar asked Oct 29 '25 22:10

Manish Patel


1 Answers

You should try next query:

final Query query = new Query(new Criteria().andOperator(
        Criteria.where("_id").is("id"),
        Criteria.where("listA").elemMatch(Criteria.where("_id").is("id"))
));

final Update update = new Update().addToSet("listA.$.listB", stuff).set("listA.$.thing", "thing");

final WriteResult wr = mongoOperations.updateFirst(query, update, "collectionName");
like image 51
Orest Avatar answered Oct 31 '25 12:10

Orest