'Spring MongoDB - update or insert array object in one operation
I have a data structure something like this:
{
"_id": "0123456789",
"myArray": [
{
"name": "Steve",
"data": {
"stuff": "datas"
}
]
}
Using Spring MongoDB, I'd like to have a findAndModify operation that either replaces the entire element (a big, complex object) found by the name field, or if it doesn't exist then insert it.
So far I have this:
private UpdateResult update(String id, String name, MyClass obj) {
Query query = new Query();
query.addCriteria(
Criteria.where("_id").is(id).andOperator(
Criteria.where("myArray.name").is(name)));
Update update = new Update();
update.set("myArray.$[]", obj);
return mongoTemplate.upsert(query, update, MyWrapperClass.class);
}
That updates the field, but it won't push a new one if it's not found
Error: Cannot apply array updates to non-array element
Is there a way to do this in one operation without querying first?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
