Nilanka Manoj
Nilanka Manoj

Reputation: 3738

collection.update query in mongo repository - spring mongo

I have my collection student :

"_id" : 1,
"marks" : [
    {
        "name" : "maths",
        "score" : 78
    },
    {
        "name" : "physics",
        "score" : 88
    }
]

I can $push marks in the shell:

db.student.update({_id:1},{$push:{marks:{type:"english", score:99}}})

I want to write this inside the StudentRepository:MongoRepository as a custom query :

@Repository
public interface StudentRepository extends MongoRepository<Student,Long> {
    @Query()//how to write this ??
    public void append(Long studentId, Mark mark);
}

Upvotes: 3

Views: 285

Answers (2)

KASMI G.
KASMI G.

Reputation: 116

The query may be something like this :

@Query(value="{}", fields = "{'_id':? =1}")
public void append(Long studentId, Mark mark);

Upvotes: 1

Alfie Danger
Alfie Danger

Reputation: 469

Have a look at this. Particularly the add to a nested array section. CustomUserRepositoryImpl is the file you should look at. For your case you could do something like this:

StudentRepository

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);
    }

Student Model

@Value @AllArgsConstructor
public class Student {

    @NonFinal @Id String studentId;
    ...
    List<Mark> marks;
    
    ...
}

Mark model

@Value @AllArgsConstructor
public class Mark {

    String type;
    int score;

}

You can also do the implementation of StudentRepository directly in that file, I just followed the format in the guide.

Upvotes: 2

Related Questions