how to insert embedded document using spring data mongodb mongotemplate

拟墨画扇 提交于 2019-12-07 05:48:02

问题


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:


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);
}


来源:https://stackoverflow.com/questions/24802391/how-to-insert-embedded-document-using-spring-data-mongodb-mongotemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!