问题
I have a MongoDB object which was created using a Map<String, List>. I'm trying to add CRUD methods to EDIT and DELETE objects from the arrays within the object. This is how the JSON structure looks like:
[
{
"id": "1",
"courses": {
"Spring": [
{
"subject": "Electrical Engineering",
. . .
"id": "123"
}
],
"Fall": [
{
"subject": "Electrical Engineering",
. . .
"id": "456"
},
{
"subject": "Computer Science",
. . .
"id": "789"
}
]
}
}
]
I was trying to use pull() method to remove the object but I get an exception
org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting to connect.
Here is the method in the Service class that tries to delete
public void delete(String semester, String id){
// Object.Array
String object = "courses." + semester;
Update update = new Update().pull(object, Collections.singletonMap("_id", id));
mongoOps.updateMulti(new Query(), update, Courses.class);
}
Courses.java
@Document
public class Courses {
@Id
private String ID;
private String semester;
. . .
}
Semester.Java
@Document
public class Semester {
@Id
String id;
Map<String, List<Courses>> courses = new HashMap<String, List<Courses>>();
...
}
回答1:
After much searching and guidance from Discord, I finally found a solution. I've probably searched all of StackOverflow and tried many implementations but nothing seemed to work. So the idea is to find the array and Query through an object value containing the id. Then, simply use an Update function according to your needs and save it with MongoTemplate.
Note that MongoDB stores id's as _id while the JSON returns it as simply id. This realization was the final step in making it work.
@Autowired
MongoTemplate mongoTemplate;
public void delete(String semester, int id){
// Set the query as Object.Array_name.property
Query query = new Query();
query.addCriteria(Criteria.where("courses.Spring._id").is("123"));
// Now, remove the entire object containing the query
Update update = new Update();
update.unset("course_list.Spring2022.$");
mongoTemplate.updateMulti(query, update, Semester.class);
}
Now, if you want to edit, the same concepts apply using the SET() function
public void edit(Courses courses) {
Query query = new Query();
query.addCriteria(Criteria.where("courses.Spring._id").is("CS332"));
Update update = new Update();
update.set("course_list.Spring2022.$", courses);
mongoTemplate.updateMulti(query, update, Semester.class);
}
来源:https://stackoverflow.com/questions/64558958/crud-operations-on-array-objects-nested-within-an-object-in-mongodb-spring-boot