Want to understand how to perform an upsert operation in an array for a given document in MongoDB.
I have the following json document
{
"firstName": "John",
"lastName": "Paul",
"contact": {
"contactGroup":"Business",
"myContacts": [{
"name": "Jeff",
"phone": "222 - 572 - 8754"
},
{
"name": "Joe",
"phone": "456 - 875 - 4521"
}
]
}
}
I want to perform the upsert operation at the following levels:
- firstName
- myContacts array
Below is the code snippet that I have worked on. currently, I am using MongoDB's addtoSet operator for myContacts but the behavior seems to perform only adds a value to an array unless the value is already present.
Person class:
@Document
public class Person{
@Id
private String id;
private String firstName;
private String lastName;
private Contact contact;
//Setter and Getter methods
}
Contact class:
public class Contact{
private String contactGroup;
private List<MyContacts> myContacts;
//Setter & Getter methods
}
MyContacts class:
public class MyContacts{
private String contactName;
private String contactPhone;
//Setter and Getter methods
}
ContactsUpdate:
public class ContacsUpdate {
@Autowired
private MongoOperations mongoOps;
// This method receives list of person objects
public void upsertMongoContact(List<Person> persons) {
for (Person person : persons) {
Update updateCmd = new Update();
Query query = new Query();
query.addCriteria((Criteria.where("firstName").is((person.firstName()))));
for (MyContacts contact : person.getContact().getmyContacts()) {
updateCmd.addToSet("contact.myContacts.", contact);
}
mongoOps.findAndModify(query, updateCmd, FindAndModifyOptions.options().upsert(true), Person.class);
}
}
}
Is there any way of updating mycontacts array based on the name. If not perform an insert operation.