@@ -24,20 +24,21 @@ public static void main(String[] args) {
24
24
MongoDatabase database = mongoClient .getDatabase ("sample_mflix" );
25
25
MongoCollection <Document > collection = database .getCollection ("movies" );
26
26
27
- Document query = new Document ().append ("title" , "Cool Runnings 2" );
27
+ // Instructs the driver to insert a new document if none match the query
28
+ UpdateOptions options = new UpdateOptions ().upsert (true );
29
+
30
+
31
+ Document updateOneQuery = new Document ().append ("title" , "Cool Runnings 2" );
28
32
29
33
// Creates instructions to update the values of three document fields
30
- Bson updates = Updates .combine (
34
+ Bson updateOneUpdates = Updates .combine (
31
35
Updates .set ("runtime" , 99 ),
32
36
Updates .addToSet ("genres" , "Sports" ),
33
37
Updates .currentTimestamp ("lastUpdated" ));
34
38
35
- // Instructs the driver to insert a new document if none match the query
36
- UpdateOptions options = new UpdateOptions ().upsert (true );
37
-
38
39
try {
39
40
// Updates the first document that has a "title" value of "Cool Runnings 2"
40
- UpdateResult result = collection .updateOne (query , updates , options );
41
+ UpdateResult result = collection .updateOne (updateOneQuery , updateOneUpdates , options );
41
42
42
43
// Prints the number of updated documents and the upserted document ID, if an upsert was performed
43
44
System .out .println ("Modified document count: " + result .getModifiedCount ());
@@ -47,6 +48,25 @@ public static void main(String[] args) {
47
48
} catch (MongoException me ) {
48
49
System .err .println ("Unable to update due to an error: " + me );
49
50
}
51
+
52
+ Bson updateManyQuery = gt ("num_mflix_comments" , 50 );
53
+
54
+ // Creates instructions to update the values of two document fields
55
+ Bson updateManyUpdates = Updates .combine (
56
+ Updates .addToSet ("genres" , "Frequently Discussed" ),
57
+ Updates .currentTimestamp ("lastUpdated" ));
58
+
59
+ try {
60
+ // Updates documents that have a "num_mflix_comments" value over 50
61
+ UpdateResult result = collection .updateMany (updateManyQuery , updateManyUpdates );
62
+
63
+ // Prints the number of updated documents
64
+ System .out .println ("Modified document count: " + result .getModifiedCount ());
65
+
66
+ // Prints a message if any exceptions occur during the operation
67
+ } catch (MongoException me ) {
68
+ System .err .println ("Unable to update due to an error: " + me );
69
+ }
50
70
}
51
71
}
52
72
}
0 commit comments