@@ -24,20 +24,21 @@ public static void main(String[] args) {
2424 MongoDatabase database = mongoClient .getDatabase ("sample_mflix" );
2525 MongoCollection <Document > collection = database .getCollection ("movies" );
2626
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" );
2832
2933 // Creates instructions to update the values of three document fields
30- Bson updates = Updates .combine (
34+ Bson updateOneUpdates = Updates .combine (
3135 Updates .set ("runtime" , 99 ),
3236 Updates .addToSet ("genres" , "Sports" ),
3337 Updates .currentTimestamp ("lastUpdated" ));
3438
35- // Instructs the driver to insert a new document if none match the query
36- UpdateOptions options = new UpdateOptions ().upsert (true );
37-
3839 try {
3940 // 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 );
4142
4243 // Prints the number of updated documents and the upserted document ID, if an upsert was performed
4344 System .out .println ("Modified document count: " + result .getModifiedCount ());
@@ -47,6 +48,25 @@ public static void main(String[] args) {
4748 } catch (MongoException me ) {
4849 System .err .println ("Unable to update due to an error: " + me );
4950 }
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+ }
5070 }
5171 }
5272}
0 commit comments