我需要在现有的事件文档中插入一个新轨道,下面是我的类结构
class Event
{
String _id;
List<Track> tracks;
}
class Track
{
String _id;
String title;
}
我现有的文档是
{
"_id":"1000",
"event_name":"Some Name"
}
文档插入后的样子
{
"_id":"1000",
"event_name":"Some name",
"tracks":
[
{
"title":"Test titile",
}
]
}
如何使用 mongoTemplate spring data mongodb 将该轨道插入到我现有的文档中?
最佳答案
首先,您必须使用 @Document
注释 Event
类:
@Document(collection = "events")
public class Event
{
// rest of code
}
添加事件的代码应如下所示:
@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);
}
}
}
注意:您应该将 Event
的类 String _id;
更改为 String id;
以便这个例子可以工作(或改变查询文字)。
编辑更新轨道也相当容易。假设您要更改第一首轨道的标题:
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);
}
关于spring - 如何使用spring data mongodb mongotemplate插入嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802391/