-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate.java
More file actions
53 lines (44 loc) · 1.8 KB
/
Update.java
File metadata and controls
53 lines (44 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.mongodb.quickstart;
import com.mongodb.quickstart.models.Grade;
import com.mongodb.quickstart.models.Score;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class Update {
@Autowired
private StudentRepository repository;
public void run() {
// Update one document by adding a comment
Grade grade = repository.findFirstByStudentId(10000d);
if (grade != null) {
Grade updatedGrade = repository.save(grade);
System.out.println("Grade updated: " + updatedGrade);
}
// Upsert a document
grade = repository.findByStudentIdAndClassId(10002d, 10d);
if (grade == null) {
grade = new Grade()
.setId(new ObjectId())
.setStudentId(10002d)
.setClassId(10d)
.setScores(List.of(new Score().setType("homework").setScore(50d)))
.setComment("You will learn a lot if you read the MongoDB blog!");
} else {
grade.getScores().add(new Score().setType("quiz").setScore(70d));
}
Grade upsertedGrade = repository.save(grade);
System.out.println("Upserted grade: " + upsertedGrade);
// Update many documents
List<Grade> grades = repository.findByStudentIdGreaterThanEqual(10001d);
repository.saveAll(grades);
System.out.println("Updated all grades with student_id >= 10001.");
// Find and update
grade = repository.findFirstByStudentId(10000d);
if (grade != null) {
Grade updated = repository.save(grade);
System.out.println("Updated grade after finding: " + updated);
}
}
}