2

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.