5

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?

1 Answer 1

5

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

That worked! Thanks! Can you please tell me how can i update specific track after addition?
i dont wana go with index while updating sub document? is there any way you update the sub document partially? it would be great help

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.