CRUD operations on Array objects nested within an Object in MongoDB Spring Boot

前端 未结 1 1400
再見小時候
再見小時候 2021-01-28 06:42

I have a MongoDB object which was created using a Map. I\'m trying to add CRUD methods to EDIT and DELETE objects from the arrays w

相关标签:
1条回答
  • 2021-01-28 07:20

    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);
           
        }
    
    0 讨论(0)
提交回复
热议问题