My collection is as below;
{
"_id" : "1",
"firstName" : "paul",
"dob" : "2012-12-12",
"friends" [ {
"_id" : "friend_1",
"firstName" : "Karan"
},
{
"_id" : "friend_2",
"firstName" : "Chasay"
}
]
}
Now I want to perform upsert
on both nested, and main document
Input Json as below
{
"_id" : "1",
"lastName" : "Cary",
"firstName" : "paul",
"dob" : "2012-12-12",
"friends" : [
{
"_id" : "friend_1",
"lastName" : "Eric"
},
{
"_id" : "friend_3",
"lastName" : "Charan"
}
]
}
Output should be
{
"_id" : "1",
"lastName" : "Cary",
"friends" : [
{
"_id" : "friend_1",
"lastName" : "Eric",
"firstName" : "Karan"
},
{
"_id" : "friend_3",
"lastName" : "Charan"
} ,
{
"_id" : "friend_2",
"firstName" : "Chasay"
}
]
}
The thing is this should be done in one query, if not possible please suggest,
What I have tried:
Query q =new Query().addCriteria(Cirtiera.where("_id").is(person.getId()));
Document doc = new Document();
template.getConverter().write(person, doc);
Update update = Update.fromDocument("$set", doc);
template.upsert(q, update, Person.class);
The above query upserts the main object, but replaces whole friends
list,
I want to use Criteria.where("_id").is(person.getId()).and("friends.id").is(person.getFriendsList().getId())
this query to make upsert in embedded array.
how can I achieve that ?
I have also posted this question in Stackoverflow: mongodb - spring data mongo upsert on embedded array of objects and main document - Stack Overflow
In summary, what I want to do is to perform upsert operations in various levels of document, like adding new item to embedded array, adding new field or changing to new value in existing field and performing $set
operation on main document.