Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert embedded document using spring data mongodb mongotemplate

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?

like image 619
Ramzan Zafar Avatar asked Jul 17 '14 11:07

Ramzan Zafar


1 Answers

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);
}
like image 129
Ori Dar Avatar answered Oct 29 '22 17:10

Ori Dar