Step 5 Project 4
Step 5 Project 4
txt
I have been hired to build Java interface for MongoDB and perform the
following tasks.
Page 1
source codes.txt
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.json.JsonWriterSettings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
/**
* find the 3 most densely populated cities in Texas.
* @param zips sample_training.zips collection from the MongoDB Sample
Dataset in MongoDB Atlas.
*/
private static void
threeMostPopulatedCitiesInTexas(MongoCollection<Document> zips) {
Bson match = match(eq("state", "TX"));
Page 1
source codes.txt
Bson group = group("$city", sum("totalPop", "$pop"));
Bson project = project(fields(excludeId(), include("totalPop"),
computed("city", "$_id")));
Bson sort = sort(descending("totalPop"));
Bson limit = limit(3);
/**
* find the 3 most popular tags and their post titles
* @param posts sample_training.posts collection from the MongoDB Sample
Dataset in MongoDB Atlas.
*/
private static void threeMostPopularTags(MongoCollection<Document>
posts) {
Bson unwind = unwind("$tags");
Bson group = group("$tags", sum("count", 1L), push("titles",
"$title"));
Bson sort = sort(descending("count"));
Bson limit = limit(3);
Bson project = project(fields(excludeId(), computed("tag", "$_id"),
include("count", "titles")));
Page 2
source codes.txt
package com.mongodb.quickstart;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.*;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import com.mongodb.quickstart.models.Grade;
import org.bson.BsonDocument;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;
import java.util.List;
import java.util.function.Consumer;
.applyConnectionString(connectionString)
.codecRegistry(codecRegistry)
.build();
Page 3
source codes.txt
MongoDatabase db = mongoClient.getDatabase("sample_training");
MongoCollection<Grade> grades = db.getCollection("grades",
Grade.class);
List<Bson> pipeline;
/**
* => Example 5: iterating using a cursor and a while loop +
remembering a resumeToken then restart the Change Streams.
* => Start "ChangeStreams" then "Update" to see some change
events.
Page 4
source codes.txt
*/
// exampleWithResumeToken(grades);
}
}
grades.watch(pipeline).resumeAfter(resumeToken).forEach(printEvent());
}
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
Page 5
source codes.txt
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.InsertManyOptions;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
MongoDatabase sampleTrainingDB =
Page 6
source codes.txt
mongoClient.getDatabase("sample_training");
MongoCollection<Document> gradesCollection =
sampleTrainingDB.getCollection("grades");
insertOneDocument(gradesCollection);
insertManyDocuments(gradesCollection);
}
}
gradesCollection.insertMany(grades, new
InsertManyOptions().ordered(false));
System.out.println("Ten grades inserted for studentId 10001.");
}
Page 7
source codes.txt
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.json.JsonWriterSettings;
// findOneAndDelete operation
filter = eq("student_id", 10002);
Document doc = gradesCollection.findOneAndDelete(filter);
System.out.println(doc.toJson(JsonWriterSettings.builder().indent(true).buil
d()));
Page 8
source codes.txt
metadata, etc).
gradesCollection.drop();
}
}
}
package com.mongodb.quickstart;
package com.mongodb.quickstart;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.FindOneAndReplaceOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.quickstart.models.Grade;
import com.mongodb.quickstart.models.Score;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import java.util.ArrayList;
import java.util.List;
Page 9
source codes.txt
ConnectionString connectionString = new
ConnectionString(System.getProperty("mongodb.uri"));
CodecRegistry pojoCodecRegistry =
fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry codecRegistry =
fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
pojoCodecRegistry);
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.codecRegistry(codecRegistry)
.build();
try (MongoClient mongoClient = MongoClients.create(clientSettings))
{
MongoDatabase db = mongoClient.getDatabase("sample_training");
MongoCollection<Grade> grades = db.getCollection("grades",
Grade.class);
Page 10
source codes.txt
grades.deleteOne(filterByGradeId));
}
}
}
package com.mongodb.quickstart;
import com.mongodb.client.*;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
Page 11
source codes.txt
System.out.println("Student list with a cursor: ");
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
.sort(descending("class_id"))
.skip(2)
.limit(2)
.into(new ArrayList<>());
package com.mongodb.quickstart;
Page 12
source codes.txt
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.json.JsonWriterSettings;
System.out.println(gradesCollection.find(filter).first().toJson(prettyPrint)
);
System.out.println(updateResult);
// upsert
filter = and(eq("student_id", 10002d), eq("class_id", 10d));
Page 13
source codes.txt
updateOperation = push("comments", "You will learn a lot if you
read the MongoDB blog!");
UpdateOptions options = new UpdateOptions().upsert(true);
updateResult = gradesCollection.updateOne(filter,
updateOperation, options);
System.out.println("\n=> Upsert document with
{\"student_id\":10002.0, \"class_id\": 10.0} because it doesn't exist
yet.");
System.out.println(updateResult);
System.out.println(gradesCollection.find(filter).first().toJson(prettyPrint)
);
// findOneAndUpdate
filter = eq("student_id", 10000);
Bson update1 = inc("x", 10); // increment x by 10. As x doesn't
exist yet, x=10.
Bson update2 = rename("class_id", "new_class_id"); // rename
variable "class_id" in "new_class_id".
Bson update3 = mul("scores.0.score", 2); // multiply the first
score in the array by 2.
Bson update4 = addToSet("comments", "This comment is uniq"); //
creating an array with a comment.
Bson update5 = addToSet("comments", "This comment is uniq"); //
using addToSet so no effect.
Bson updates = combine(update1, update2, update3, update4,
update5);
// returns the old version of the document before the update.
Document oldVersion = gradesCollection.findOneAndUpdate(filter,
updates);
System.out.println("\n=> FindOneAndUpdate operation. Printing
the old version by default:");
System.out.println(oldVersion.toJson(prettyPrint));
Page 14
source codes.txt
FindOneAndUpdateOptions optionAfter = new
FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER);
Document newVersion = gradesCollection.findOneAndUpdate(filter,
updates, optionAfter);
System.out.println("\n=> FindOneAndUpdate operation. But we can
also ask for the new version of the doc:");
System.out.println(newVersion.toJson(prettyPrint));
}
}
}
package com.mongodb.quickstart.models;
import org.bson.codecs.pojo.annotations.BsonProperty;
import org.bson.types.ObjectId;
import java.util.List;
import java.util.Objects;
Page 15
source codes.txt
return this;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Grade{");
sb.append("id=").append(id);
sb.append(", student_id=").append(studentId);
sb.append(", class_id=").append(classId);
sb.append(", scores=").append(scores);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Grade grade = (Grade) o;
return Objects.equals(id, grade.id) && Objects.equals(studentId,
grade.studentId) && Objects.equals(classId,
Page 16
source codes.txt
}
@Override
public int hashCode() {
return Objects.hash(id, studentId, classId, scores);
}
}
package com.mongodb.quickstart.models;
import java.util.Objects;
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Score{");
sb.append("type='").append(type).append('\'');
sb.append(", score=").append(score);
sb.append('}');
return sb.toString();
}
Page 17
source codes.txt
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Score score1 = (Score) o;
return Objects.equals(type, score1.type) && Objects.equals(score,
score1.score);
}
@Override
public int hashCode() {
return Objects.hash(type, score);
}
}
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -
%msg%n</pattern>
</encoder>
</appender>
<root level="warn">
<appender-ref ref="STDOUT" />
</root>
</configuration>
<groupId>com.mongodb</groupId>
<artifactId>java-quick-start</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
Page 18
source codes.txt
<maven-compiler-plugin.source>8</maven-compiler-plugin.source>
<maven-compiler-plugin.target>8</maven-compiler-plugin.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mongodb-driver-sync.version>4.1.1</mongodb-driver-sync.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>${mongodb-driver-sync.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.3.0-alpha5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.target}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Command lines
Compile:
mvn clean compile
Run the HelloMongoDB class:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.HelloMongoDB"
Run the Connection class:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Connection"
Page 19
source codes.txt
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Run the Create class:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Create"
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Run the Read class:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Read"
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Run the Update class:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Update"
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Run the Delete class:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Delete"
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Run the MappingPOJO class:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.MappingPOJO"
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Run the AggregationFramework class:
mvn compile exec:java
-Dexec.mainClass="com.mongodb.quickstart.AggregationFramework"
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Run the ChangeStreams class:
mvn compile exec:java
-Dexec.mainClass="com.mongodb.quickstart.ChangeStreams"
-Dmongodb.uri=mongodb+srv://USERNAME:[email protected]/tes
t?w=majority
Page 20
java-quick-start/
├── pom.xml
└── src
└── main
└── java
└── com
└── mongodb
└── quickstart
To verify that everything works correctly, you should be able to create and run a
simple "Hello MongoDB!" program. In src/main/java/com/mongodb/quickstart,
create the HelloMongoDB.java file:
package com.mongodb.quickstart;
public class HelloMongoDB {
public static void main(String[] args) {
System.out.println("Hello MongoDB!");
}
}
Then compile and execute it with your IDE or use the command line in the root
directory (where the src folder is):
[...]
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.mongodb:java-quick-start >--------------------
[INFO] Building java-quick-start 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-
quick-start ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ java-quick-
start ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ java-quick-start ---
Hello MongoDB!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.786 s
[INFO] Finished at: 2019-10-02T20:19:36+02:00
[INFO] ------------------------------------------------------------------------
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class Connection {
public static void main(String[] args) {
String connectionString = System.getProperty("mongodb.uri");
try (MongoClient mongoClient = MongoClients.create(connectionString)) {
List<Document> databases = mongoClient.listDatabases().into(new
ArrayList<>());
databases.forEach(db -> System.out.println(db.toJson()));
}
}
}
Extended JSON is the human readable version of a BSON document without loss
of type information. You can read more about the Java driver and BSON in the
MongoDB java driver documentation.
{
"_id": {
"$oid": "56d5f7eb604eb380b0d8d8ce"
},
"student_id": {
"$numberDouble": "0"
},
"scores": [{
"type": "exam",
"score": {
"$numberDouble": "78.40446309504266"
}
}, {
"type": "quiz",
"score": {
"$numberDouble": "73.36224783231339"
}
}, {
"type": "homework",
"score": {
"$numberDouble": "46.980982486720535"
}
}, {
"type": "homework",
"score": {
"$numberDouble": "76.67556138656222"
}
}],
"class_id": {
"$numberDouble": "339"
}
}
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class Create {
public static void main(String[] args) {
try (MongoClient mongoClient =
MongoClients.create(System.getProperty("mongodb.uri"))) {
MongoDatabase sampleTrainingDB =
mongoClient.getDatabase("sample_training");
MongoCollection<Document> gradesCollection =
sampleTrainingDB.getCollection("grades");
}
}
}
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.Random;
import static java.util.Arrays.asList;
public class Create {
public static void main(String[] args) {
try (MongoClient mongoClient =
MongoClients.create(System.getProperty("mongodb.uri"))) {
MongoDatabase sampleTrainingDB =
mongoClient.getDatabase("sample_training");
MongoCollection<Document> gradesCollection =
sampleTrainingDB.getCollection("grades");
Random rand = new Random();
Document student = new Document("_id", new ObjectId());
student.append("student_id", 10000d)
.append("class_id", 1d)
.append("scores", asList(new Document("type", "exam").append("score",
rand.nextDouble() * 100),
new Document("type", "quiz").append("score", rand.nextDouble() * 100),
new Document("type", "homework").append("score", rand.nextDouble() * 100),
new Document("type", "homework").append("score", rand.nextDouble() * 100)));
gradesCollection.insertOne(student);
}
}
}
{
"_id": {
"$oid": "5d97c375ded5651ea3462d0f"
},
"student_id": {
"$numberDouble": "10000"
},
"class_id": {
"$numberDouble": "1"
},
"scores": [{
"type": "exam",
"score": {
"$numberDouble": "4.615256396625178"
}
}, {
"type": "quiz",
"score": {
"$numberDouble": "73.06173415145801"
}
}, {
"type": "homework",
"score": {
"$numberDouble": "19.378205578990727"
}
}, {
"type": "homework",
"score": {
"$numberDouble": "82.3089189278531"
}
}]
}
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.InsertManyOptions;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static java.util.Arrays.asList;
public class Create {
private static final Random rand = new Random();
public static void main(String[] args) {
try (MongoClient mongoClient =
MongoClients.create(System.getProperty("mongodb.uri"))) {
MongoDatabase sampleTrainingDB =
mongoClient.getDatabase("sample_training");
MongoCollection<Document> gradesCollection =
sampleTrainingDB.getCollection("grades");
insertOneDocument(gradesCollection);
insertManyDocuments(gradesCollection);
}
}
private static void insertOneDocument(MongoCollection<Document>
gradesCollection) {
gradesCollection.insertOne(generateNewGrade(10000d, 1d));
System.out.println("One grade inserted for studentId 10000.");
}
private static void insertManyDocuments(MongoCollection<Document>
gradesCollection) {
List<Document> grades = new ArrayList<>();
for (double classId = 1d; classId <= 10d; classId++) {
grades.add(generateNewGrade(10001d, classId));
}
gradesCollection.insertMany(grades, new InsertManyOptions().ordered(false));
System.out.println("Ten grades inserted for studentId 10001.");
}
private static Document generateNewGrade(double studentId, double classId) {
List<Document> scores = asList(new Document("type", "exam").append("score",
rand.nextDouble() * 100),
new Document("type", "quiz").append("score", rand.nextDouble() * 100),
new Document("type", "homework").append("score", rand.nextDouble() * 100),
new Document("type", "homework").append("score", rand.nextDouble() * 100));
return new Document("_id", new ObjectId()).append("student_id", studentId)
.append("class_id", classId)
.append("scores", scores);
}
}
package com.mongodb.quickstart;
import com.mongodb.client.*;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.descending;
public class Read {
public static void main(String[] args) {
try (MongoClient mongoClient =
MongoClients.create(System.getProperty("mongodb.uri"))) {
MongoDatabase sampleTrainingDB =
mongoClient.getDatabase("sample_training");
MongoCollection<Document> gradesCollection =
sampleTrainingDB.getCollection("grades");
// find one document with new Document
Document student1 = gradesCollection.find(new Document("student_id",
10000)).first();
System.out.println("Student 1: " + student1.toJson());
}
}
}
// without helpers
gradesCollection.find(new Document("student_id", new Document("$gte",
10000)));
// with the Filters.gte() helper
gradesCollection.find(gte("student_id", 10000));
Lists
Lists are usually easier to manipulate than iterators, so we can also do this to
retrieve directly an ArrayList<Document>:
Consumers
We could also use a Consumer which is a functional interface:
Cursors, Sort, Skip, Limit, and Projections
As we saw above with the Iterator example, MongoDB leverages cursors to
iterate through your result set.
When I run an explain on this query, this is the winning plan I get:
"winningPlan" : {
"stage" : "LIMIT",
"limitAmount" : 2,
"inputStage" : {
"stage" : "PROJECTION_COVERED",
"transformBy" : {
"_id" : 0,
"class_id" : 1,
"student_id" : 1
},
"inputStage" : {
"stage" : "SKIP",
"skipAmount" : 2,
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"student_id" : 1,
"class_id" : -1
},
"indexName" : "student_id_1_class_id_-1",
"isMultiKey" : false,
"multiKeyPaths" : {
"student_id" : [ ],
"class_id" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"student_id" : [
"[10001.0, 10001.0]"
],
"class_id" : [
"[5.0, -inf.0]"
]
}
}
}
}
}
Update Operations
Update One Document
Let's edit the document with {student_id: 10000}. To achieve this, we will use the
method updateOne.
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.json.JsonWriterSettings;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.*;
public class Update {
public static void main(String[] args) {
JsonWriterSettings prettyPrint = JsonWriterSettings.builder().indent(true).build();
try (MongoClient mongoClient =
MongoClients.create(System.getProperty("mongodb.uri"))) {
MongoDatabase sampleTrainingDB =
mongoClient.getDatabase("sample_training");
MongoCollection<Document> gradesCollection =
sampleTrainingDB.getCollection("grades");
// update one document
Bson filter = eq("student_id", 10000);
Bson updateOperation = set("comment", "You should learn MongoDB!");
UpdateResult updateResult = gradesCollection.updateOne(filter,
updateOperation);
System.out.println("=> Updating the doc with {\"student_id\":10000}. Adding
comment.");
System.out.println(gradesCollection.find(filter).first().toJson(prettyPrint));
System.out.println(updateResult);
}
}
}
filter = and(eq("student_id", 10002d), eq("class_id", 10d));
updateOperation = push("comments", "You will learn a lot if you read the
MongoDB blog!");
UpdateOptions options = new UpdateOptions().upsert(true);
updateResult = gradesCollection.updateOne(filter, updateOperation, options);
System.out.println("\n=> Upsert document with {\"student_id\":10002.0,
\"class_id\": 10.0} because it doesn't exist yet.");
System.out.println(updateResult);
System.out.println(gradesCollection.find(filter).first().toJson(prettyPrint));
As you can see, I'm using the third parameter of the update operation to set the
option upsert to true.
I'm also using here the static method Updates.push() to push a new value in my
array c