Reputation: 211
I want to insert into an array-list in an embedded data. I tried several ways but couldn't make it out. My data structure is something like this. The code given here is just a dummy reference to my original data structure
Class X{
Integer _id;
Arraylist<Y> objY;
}
Class Y{
Integer _id;
Arraylist<Z> objZ;
}
Class Z{
Integer _id;
String value;
String oldValue
}
I want to insert a new data into objZ I know the id value of Class X an Y. I am using Spring mongotemplate. Does Spring Mongo Template Supports this? Can someone help me out through this.
Thanks in advance.
Upvotes: 2
Views: 97
Reputation: 211
I got it hope it might help someone out here, Use aggregetion to do this.
Query searchUserQuery = new Query((Criteria.where("_id").is("542264c8e4b098972a1cf60c").and("leads._id").is("2")));// _id is the id of class X
AggregationOperation match = Aggregation.match(searchUserQuery );
AggregationOperation group = Aggregation.group("objY");
Aggregation aggregation = Aggregation.newAggregation(Aggregation.unwind("objY"),match, group);
List<objY> asd=mongoOperation.aggregate(aggregation, "Name_of_ur_collection", B.class).getMappedResults();
ArrayList<Z> s=asd.get(0).getObjZ();
s.add("New Data to be added");
mongoOperation.updateFirst(searchUserQuery, Update.update("objY.$.objZ", s), X.class);
This will insert your array list in class Y.
Thanks
Upvotes: 3