As you can see from docs:
The mapping framework does not handle cascading saves. If you change an Account object that is referenced by a Person object, you must save the Account object separately. Calling save on the Person object will not automatically save the Account objects in the property accounts.
So, first, you have to save each object of the otherPojos list. After that you can save MyPojo instance:
MyPojo pojo = new MyPojo();
OtherPojo otherPojo = new OtherPojo();
OtherPojo otherPojo1 = new OtherPojo();
pojo.setOtherPojos(Arrays.asList(otherPojo, otherPojo1));
mongoTemplate.save(otherPojo);
mongoTemplate.save(otherPojo1);
mongoTemplate.save(pojo);
UPDATED: You saved a objects:
for( MyPojo pojo : somePojoList ){
for( OtherPojo otherPojo : pojo.getOtherPojos() ){
mongoTemplate.save( otherPojo,collectionname );
}
}
All otherPojo objects will be saved in collection with name "collectionName"..
but your myPojo objects have a $ref to an otherPojo collection..
"otherPojo" : [
{
"$ref" : "otherPojo",
"$id" : ObjectId("535f9100ad52e59815755cef")
},
{
"$ref" : "otherPojo",
"$id" : ObjectId("535f9101ad52e59815755cf0")
}
]
So, "collectionname" variable
mongoTemplate.save( otherPojo,collectionname );
must be "otherPojo".
To avoid confusion, I propose to specify a collection for saving OtherPojo objects with @Doucument annotation:
@Document(collection="otherPojos")
public class OtherPojo{
@Id
private ObjectId _id;
private String someOtherFields;
}
And to save otherPojo objects by using a overloaded save() method of mongoTemplate
mongoTemplate.save( otherPojo );
In this way , you will have a valid $ref for myPojo documents
UPDATE 2:
In this case, you want to store parents and childs object in same collection.
To achieve this you can use this approach