java - mongo 存储库中的 collection.update 查询 - spring mongo

标签 java mongodb spring-boot

我有我的 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);
}
StudentRepositoryImpl
public 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/

相关文章:

node.js - Nodejs Mongodb : findByIdAndUpdate not returning correct error

java - JPA 存储库上的 Spring 重试

java - 如何在 Spring Boot 中 Autowiring OkHttpClient bean?

java - 如何正确释放Android MediaPlayer

java - 使用 FlyingSaucer 将包含阿拉伯字符的 HTML 页面转换为 PDF

java - Play + Ebean : Changes to the model + database

java - ImageMagick在Spring boot的打包WAR中找不到convert.exe的路径

java - 尝试从 Android 中的 uri 读取时出现文件未找到异常

python - pymongo 插入 vs pymysql 插入

javascript - 通过id更新object中的MongoDB对象