Skip to content

DOCSP-33345: Java comments pt. 3 #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions source/includes/usage-examples/code-snippets/ReplaceOne.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Replaces the first document that matches a filter by using the Java driver

package usage.examples;

import static com.mongodb.client.model.Filters.eq;
Expand All @@ -20,23 +22,27 @@ public static void main(String[] args) {
String uri = "<connection string uri>";

try (MongoClient mongoClient = MongoClients.create(uri)) {

MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");

Bson query = eq("title", "Music of the Heart");

// Creates a new document containing "title" and "fullplot" fields
Document replaceDocument = new Document().
append("title", "50 Violins").
append("fullplot", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music");

// Instructs the driver to insert a new document if none match the query
ReplaceOptions opts = new ReplaceOptions().upsert(true);

// Replaces the first document that matches the filter with a new document
UpdateResult result = collection.replaceOne(query, replaceDocument, opts);

// Prints the number of modified documents and the upserted document ID, if an upsert was performed
System.out.println("Modified document count: " + result.getModifiedCount());
System.out.println("Upserted id: " + result.getUpsertedId()); // only contains a value when an upsert is performed
System.out.println("Upserted id: " + result.getUpsertedId());

// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to replace due to an error: " + me);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Updates documents that match a query filter by using the Java driver

package usage.examples;

import static com.mongodb.client.model.Filters.gt;
Expand All @@ -20,21 +22,24 @@ public static void main(String[] args) {
String uri = "<connection string uri>";

try (MongoClient mongoClient = MongoClients.create(uri)) {

MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");

Bson query = gt("num_mflix_comments", 50);

// Creates instructions to update the values of two document fields
Bson updates = Updates.combine(
Updates.addToSet("genres", "Frequently Discussed"),
Updates.currentTimestamp("lastUpdated"));

try {
// Updates documents that have a "num_mflix_comments" value over 50
UpdateResult result = collection.updateMany(query, updates);

// Prints the number of updated documents
System.out.println("Modified document count: " + result.getModifiedCount());

// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to update due to an error: " + me);
}
Expand Down
12 changes: 9 additions & 3 deletions source/includes/usage-examples/code-snippets/UpdateOne.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Updates the first document that matches a query filter by using the Java driver

package usage.examples;

import org.bson.Document;
Expand All @@ -19,25 +21,29 @@ public static void main(String[] args) {
String uri = "<connection string uri>";

try (MongoClient mongoClient = MongoClients.create(uri)) {

MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");

Document query = new Document().append("title", "Cool Runnings 2");

// Creates instructions to update the values of three document fields
Bson updates = Updates.combine(
Updates.set("runtime", 99),
Updates.addToSet("genres", "Sports"),
Updates.currentTimestamp("lastUpdated"));

// Instructs the driver to insert a new document if none match the query
UpdateOptions options = new UpdateOptions().upsert(true);

try {
// Updates the first document that has a "title" value of "Cool Runnings 2"
UpdateResult result = collection.updateOne(query, updates, options);

// Prints the number of updated documents and the upserted document ID, if an upsert was performed
System.out.println("Modified document count: " + result.getModifiedCount());

System.out.println("Upserted id: " + result.getUpsertedId()); // only contains a value when an upsert is performed
System.out.println("Upserted id: " + result.getUpsertedId());

// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to update due to an error: " + me);
}
Expand Down
18 changes: 16 additions & 2 deletions source/includes/usage-examples/code-snippets/Watch.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
/**
* This file demonstrates how to open a change stream by using the Java driver.
* It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens
* to change events in the "movies" collection. The code uses a change stream with a pipeline
* to only filter for "insert" and "update" events.
*/

package usage.examples;

import java.util.Arrays;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

Expand All @@ -18,18 +28,22 @@ public static void main( String[] args ) {
String uri = "<connection string uri>";

try (MongoClient mongoClient = MongoClients.create(uri)) {

MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");

// Creates instructions to match insert and update operations
List<Bson> pipeline = Arrays.asList(
Aggregates.match(
Filters.in("operationType",
Arrays.asList("insert", "update"))));

// Creates a change stream that receives change events for the specified operations
ChangeStreamIterable<Document> changeStream = database.watch(pipeline)
.fullDocument(FullDocument.UPDATE_LOOKUP);
// variables referenced in a lambda must be final; final array gives us a mutable integer

final int[] numberOfEvents = {0};

// Prints a message each time the change stream receives a change event, until it receives two events
changeStream.forEach(event -> {
System.out.println("Received a change to the collection: " + event);
if (++numberOfEvents[0] >= 2) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// Performs CRUD operations to generate change events when run with the Watch application


package usage.examples;

import java.util.Arrays;
Expand All @@ -18,19 +21,23 @@ public static void main(String[] args) {
String uri = "<connection string uri>";

try (MongoClient mongoClient = MongoClients.create(uri)) {

MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");

try {
// Inserts a sample document into the "movies" collection and print its ID
InsertOneResult insertResult = collection.insertOne(new Document("test", "sample movie document"));
System.out.println("Success! Inserted document id: " + insertResult.getInsertedId());

// Updates the sample document and prints the number of modified documents
UpdateResult updateResult = collection.updateOne(new Document("test", "sample movie document"), Updates.set("field2", "sample movie document update"));
System.out.println("Updated " + updateResult.getModifiedCount() + " document.");

// Deletes the sample document and prints the number of deleted documents
DeleteResult deleteResult = collection.deleteOne(new Document("field2", "sample movie document update"));
System.out.println("Deleted " + deleteResult.getDeletedCount() + " document.");

// Prints a message if any exceptions occur during the operations
} catch (MongoException me) {
System.err.println("Unable to insert, update, or replace due to an error: " + me);
}
Expand Down