Ram*_*far 5 spring mongodb spring-data-mongodb
我需要在现有的事件文档中插入一个新轨道,以下是我的类结构
class Event
{
String _id;
List<Track> tracks;
}
class Track
{
String _id;
String title;
}
Run Code Online (Sandbox Code Playgroud)
我现有的文件是
{
"_id":"1000",
"event_name":"Some Name"
}
Run Code Online (Sandbox Code Playgroud)
插入后文档看起来像
{
"_id":"1000",
"event_name":"Some name",
"tracks":
[
{
"title":"Test titile",
}
]
}
Run Code Online (Sandbox Code Playgroud)
如何使用mongoTemplate spring data mongodb将该轨道插入到我现有的文档中?
首先,您必须使用以下内容注释Event类@Document:
@Document(collection = "events")
public class Event
{
// rest of code
}
Run Code Online (Sandbox Code Playgroud)
添加事件的代码应如下所示:
@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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您应该改变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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7522 次 |
| 最近记录: |