I need to insert a new track into the existing event document following is my class structure
class Event
{ 
    String _id; 
    List<Track> tracks;
}
class Track
{
    String _id;
    String title;
}
My existing document is
{
  "_id":"1000",
  "event_name":"Some Name"
}
document will look like after insertion
{
  "_id":"1000",
  "event_name":"Some name",  
  "tracks":
   [
     {
        "title":"Test titile",
     }
  ]
}
How can i insert that track into my existing document using mongoTemplate spring data mongodb?
First, you have to annotate Event class with @Document:
@Document(collection = "events")
public class Event
{
    // rest of code
}
The code for adding an event should look like this:
@Repository
public class EventsDao {
    @Autowired
    MongoOperations template;
    public void addTrack(Track t) {
        Event e = template.findOne
            (new Query(Criteria.where("id").is("1000")), Event.class);
        if (e != null) {
            e.getTracks().add(t);
            template.save(e);
        }
    }
}
Note : You should change Event's class String _id; to String id; in order for this example to work (or change the query literal).
Edit update a track is also fairly easy. Suppose you want to change the first track's title:
Event e = template.findOne(new Query(Criteria.where("_id").is("1000")), Event.class);
if (e != null) {
    e.getTracks().get(0).setTitle("when i'm 64");
    template.save(e);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With