但是在Spring引导中很好。我想在嵌入式文档中使用CRUD操作。我尽了最大努力使用Spring Boot,但是今天没有运气。我尝试的结构如下。我需要更新类别2,删除类别3,最后添加新类别。
文档
@Document(collection="reel")
public class Reel{
@Id
private ObjectId _id;
private String name;
List<Category> category;
// No arg & arg constructoe, getters and setters
}
// I haven't use @Document
public class category{
ptivate ObjectId _id=new ObjectId();
private String categoryName;
private String type;
// No arg & arg constructoe, getters and setters
}
我拥有的结构,
{
"_id": {
"$oid": "5e8426717a16fb5b755edebd"
},
"name": "Name",
"category": [
{
"_id": {
"$oid": "5e8453c88056df756a242cd8"
},
"categoryName": "category 1",
"type": "type 1"
},
{
"_id": {
"$oid": "5e8453c88056df756a242csd8"
},
"categoryName": "category 2",
"type": "type 2"
},
{
"_id": {
"$oid": "5e8453c8805sd756a242cd8"
},
"categoryName": "category 3",
"type": "type 3"
}
],
"_class": "com.videoappservice.model.Reel"
}
无论我如何尝试这样更新,
public Category updateReelCategoryById(ObjectId id, String categoryName, String categoryType) {
// Here I pass ID of category
Query query=new Query().addCriteria(Criteria.where("_id").is(id));
Update update= new Update()
.set("reel.category.type",categoryType)
.set("reel.category.categoryName",categoryName);
Category result=mongoTemplate.findAndModify(query,update, Category.class);
return result;
}
谢谢。请让我知道我的建模是否正确
您尝试得很好...以下是一些小的更正。
Query query=new Query().addCriteria(Criteria.where("category").elemMatch(Criteria.where("_id").is(id)));
Update update = new Update()
.set("category.$.type", categoryType)
.set("category.$.description", categoryDescription);
UpdateResult result = mongoTemplate.updateFirst(query, update, Reel.class);