Search code examples
javaspringmongodbmongotemplatemongorepository

How to insert values in an inner arraylist while updating outer arraylist in mongodb?


I am working with Spring MongoDB and now I'm facing a problem for inserting values into an arraylist. Here is my POJO class structure...

public class Search implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    private String id;
    private String searchkey;
    private ArrayList<Lead> leads;
 }

"Lead" is another POJO class which is like...

public class Lead implements Serializable {

private static final long serialVersionUID = 1L;
private String leadtext;
private String address;
private ArrayList<History> trackrecords;
}

"History" is anther POJO class which is like..

public class History implements Serializable {

private static final long serialVersionUID = 1L;
private String id;
private String changedfield;
private String oldvalue;
private String newvalue;
}

and the problem is i want to insert data into trackrecords while updating one lead. is it possible in spring mongotemplate..?? if it is possible then please help me. Thank you in advance


Solution

  • Please try this.

    Suppose leadtext can locate that lead element uniquely.

    Query query = new Query().addCriteria(Query.where("searchkey").is(searchkey).and("leads.leadtext").is(leadtext));
    Update update = new Update().push("leads.$.trackrecords", trackrecord);
    mongoTemplate.updateFirst(query, update, Search.class);