我有我的 Collection 学生:
"_id" : 1,
"marks" : [
{
"name" : "maths",
"score" : 78
},
{
"name" : "physics",
"score" : 88
}
]
我可以 $push
shell 中的标记:db.student.update({_id:1},{$push:{marks:{type:"english", score:99}}})
我想在 StudentRepository:MongoRepository 中写这个作为自定义查询:@Repository
public interface StudentRepository extends MongoRepository<Student,Long> {
@Query()//how to write this ??
public void append(Long studentId, Mark mark);
}
最佳答案
看看this .特别是添加到嵌套数组部分。 CustomUserRepositoryImpl是您应该查看的文件。对于您的情况,您可以执行以下操作:
学生资料库
public interface StudentRepository {
Mono<Student> addMarks (String studentId, String type, int score);
}
StudentRepositoryImplpublic class StudentRepositoryImpl implements StudentRepository {
private final ReactiveMongoTemplate mongoTemplate;
@Autowired
public StudentRepositoryImpl(ReactiveMongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@Override
public Mono<Student> addMarks (String studentId, String type, int score) {
Query query = new Query(Criteria.where("_id").is(studentId));
Update update = new Update().addToSet("marks", new Mark(type, score);
return mongoTemplate.findAndModify(query, update, Student.class);
}
学生模特@Value @AllArgsConstructor
public class Student {
@NonFinal @Id String studentId;
...
List<Mark> marks;
...
}
马克模型@Value @AllArgsConstructor
public class Mark {
String type;
int score;
}
您也可以直接在该文件中执行 StudentRepository 的实现,我只是按照指南中的格式进行操作。
关于java - mongo 存储库中的 collection.update 查询 - spring mongo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62186781/