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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With