0% found this document useful (0 votes)
57 views39 pages

Step 5 Project 4

use the content and benefit from using it, study the content and apply what is learned, make and distribute copies of the content, change and improve the content and distribute these derivative works

Uploaded by

SUDHEER REDDY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views39 pages

Step 5 Project 4

use the content and benefit from using it, study the content and apply what is learned, make and distribute copies of the content, change and improve the content and distribute these derivative works

Uploaded by

SUDHEER REDDY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

writeup.

txt
I have been hired to build Java interface for MongoDB and perform the
following tasks.

Interact with the sharded system using Java application.


Insert new documents from Java application for different sources in the
database and see if data is distributed on different shards.
Find total call charges for all records and its query behavior.
Find number of calls made from each location and its query behavior.
Find revenue generated for each location and its query behavior.

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;

import static com.mongodb.client.model.Accumulators.push;


import static com.mongodb.client.model.Accumulators.sum;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.descending;

public class AggregationFramework {

public static void main(String[] args) {


String connectionString = System.getProperty("mongodb.uri");
try (MongoClient mongoClient =
MongoClients.create(connectionString)) {
MongoDatabase db = mongoClient.getDatabase("sample_training");
MongoCollection<Document> zips = db.getCollection("zips");
MongoCollection<Document> posts = db.getCollection("posts");
threeMostPopulatedCitiesInTexas(zips);
threeMostPopularTags(posts);
}
}

/**
* 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);

List<Document> results = zips.aggregate(Arrays.asList(match, group,


project, sort, limit))
.into(new ArrayList<>());
System.out.println("==> 3 most densely populated cities in Texas");
results.forEach(printDocuments());
}

/**
* 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")));

List<Document> results = posts.aggregate(Arrays.asList(unwind,


group, sort, limit, project)).into(new ArrayList<>());
System.out.println("==> 3 most popular tags and their posts
titles");
results.forEach(printDocuments());
}

private static Consumer<Document> printDocuments() {


return doc ->
System.out.println(doc.toJson(JsonWriterSettings.builder().indent(true).buil
d()));
}
}

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;

import static com.mongodb.client.model.Aggregates.match;


import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.in;
import static
com.mongodb.client.model.changestream.FullDocument.UPDATE_LOOKUP;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class ChangeStreams {

public static void main(String[] args) {


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))


{

Page 3
source codes.txt
MongoDatabase db = mongoClient.getDatabase("sample_training");
MongoCollection<Grade> grades = db.getCollection("grades",
Grade.class);
List<Bson> pipeline;

// Only uncomment one example at a time. Follow instructions for


each individually then kill all remaining processes.

/** => Example 1: print all the write operations.


* => Start "ChangeStreams" then "MappingPOJOs" to see some
change events.
*/
grades.watch().forEach(printEvent());

/** => Example 2: print only insert and delete operations.


* => Start "ChangeStreams" then "MappingPOJOs" to see some
change events.
*/
// pipeline = singletonList(match(in("operationType",
asList("insert", "delete"))));
// grades.watch(pipeline).forEach(printEvent());

/** => Example 3: print only updates without fullDocument.


* => Start "ChangeStreams" then "Update" to see some change
events (start "Create" before if not done earlier).
*/
// pipeline = singletonList(match(eq("operationType",
"update")));
// grades.watch(pipeline).forEach(printEvent());

/** => Example 4: print only updates with fullDocument.


* => Start "ChangeStreams" then "Update" to see some change
events.
*/
// pipeline = singletonList(match(eq("operationType",
"update")));
//
grades.watch(pipeline).fullDocument(UPDATE_LOOKUP).forEach(printEvent());

/**
* => 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);
}
}

private static void exampleWithResumeToken(MongoCollection<Grade>


grades) {
List<Bson> pipeline = singletonList(match(eq("operationType",
"update")));
ChangeStreamIterable<Grade> changeStream = grades.watch(pipeline);
MongoChangeStreamCursor<ChangeStreamDocument<Grade>> cursor =
changeStream.cursor();
System.out.println("==> Going through the stream a first time &
record a resumeToken");
int indexOfOperationToRestartFrom = 5;
int indexOfIncident = 8;
int counter = 0;
BsonDocument resumeToken = null;
while (cursor.hasNext() && counter != indexOfIncident) {
ChangeStreamDocument<Grade> event = cursor.next();
if (indexOfOperationToRestartFrom == counter) {
resumeToken = event.getResumeToken();
}
System.out.println(event);
counter++;
}
System.out.println("==> Let's imagine something wrong happened and I
need to restart my Change Stream.");
System.out.println("==> Starting from resumeToken=" + resumeToken);
assert resumeToken != null;

grades.watch(pipeline).resumeAfter(resumeToken).forEach(printEvent());
}

private static Consumer<ChangeStreamDocument<Grade>> printEvent() {


return System.out::println;
}
}

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;

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()));
}
}
}

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 =

Page 6
source codes.txt
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);
}
}

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;

import static com.mongodb.client.model.Filters.eq;


import static com.mongodb.client.model.Filters.gte;

public class Delete {

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");

// delete one document


Bson filter = eq("student_id", 10000);
DeleteResult result = gradesCollection.deleteOne(filter);
System.out.println(result);

// findOneAndDelete operation
filter = eq("student_id", 10002);
Document doc = gradesCollection.findOneAndDelete(filter);

System.out.println(doc.toJson(JsonWriterSettings.builder().indent(true).buil
d()));

// delete many documents


filter = gte("student_id", 10000);
result = gradesCollection.deleteMany(filter);
System.out.println(result);

// delete the entire collection and its metadata (indexes, chunk

Page 8
source codes.txt
metadata, etc).
gradesCollection.drop();
}
}
}

package com.mongodb.quickstart;

public class HelloMongoDB {

public static void main(String[] args) {


System.out.println("Hello MongoDB!");
}
}

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;

import static com.mongodb.client.model.Filters.eq;


import static java.util.Collections.singletonList;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class MappingPOJO {

public static void main(String[] args) {

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);

// create a new grade.


Grade newGrade = new Grade().setStudentId(10003d)
.setClassId(10d)
.setScores(singletonList(new
Score().setType("homework").setScore(50d)));
grades.insertOne(newGrade);
System.out.println("Grade inserted.");

// find this grade.


Grade grade = grades.find(eq("student_id", 10003d)).first();
System.out.println("Grade found:\t" + grade);

// update this grade: adding an exam grade


List<Score> newScores = new ArrayList<>(grade.getScores());
newScores.add(new Score().setType("exam").setScore(42d));
grade.setScores(newScores);
Document filterByGradeId = new Document("_id", grade.getId());
FindOneAndReplaceOptions returnDocAfterReplace = new
FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER);
Grade updatedGrade = grades.findOneAndReplace(filterByGradeId,
grade, returnDocAfterReplace);
System.out.println("Grade replaced:\t" + updatedGrade);

// delete this grade


System.out.println("Grade deleted:\t" +

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;

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());

// find one document with Filters.eq()


Document student2 = gradesCollection.find(eq("student_id",
10000)).first();
System.out.println("Student 2: " + student2.toJson());

// find a list of documents and iterate throw it using an


iterator.
FindIterable<Document> iterable =
gradesCollection.find(gte("student_id", 10000));
MongoCursor<Document> cursor = iterable.iterator();

Page 11
source codes.txt
System.out.println("Student list with a cursor: ");
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}

// find a list of documents and use a List object instead of an


iterator
List<Document> studentList =
gradesCollection.find(gte("student_id", 10000)).into(new ArrayList<>());
System.out.println("Student list with an ArrayList:");
for (Document student : studentList) {
System.out.println(student.toJson());
}

// find a list of documents and print using a consumer


System.out.println("Student list using a Consumer:");
Consumer<Document> printConsumer = document ->
System.out.println(document.toJson());
gradesCollection.find(gte("student_id",
10000)).forEach(printConsumer);

// find a list of documents with sort, skip, limit and


projection
List<Document> docs = gradesCollection.find(and(eq("student_id",
10001), lte("class_id", 5)))

.projection(fields(excludeId(), include("class_id", "student_id")))

.sort(descending("class_id"))
.skip(2)
.limit(2)
.into(new ArrayList<>());

System.out.println("Student sorted, skipped, limited and


projected: ");
for (Document student : docs) {
System.out.println(student.toJson());
}
}
}
}

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;

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);

// 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)
);

// update many documents


filter = eq("student_id", 10001);
updateResult = gradesCollection.updateMany(filter,
updateOperation);
System.out.println("\n=> Updating all the documents with
{\"student_id\":10001}.");
System.out.println(updateResult);

// 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));

// but I can also request the new version


filter = eq("student_id", 10001);

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;

public class Grade {

private ObjectId id;


@BsonProperty(value = "student_id")
private Double studentId;
@BsonProperty(value = "class_id")
private Double classId;
private List<Score> scores;

public ObjectId getId() {


return id;
}

public Grade setId(ObjectId id) {


this.id = id;
return this;
}

public Double getStudentId() {


return studentId;
}

public Grade setStudentId(Double studentId) {


this.studentId = studentId;

Page 15
source codes.txt
return this;
}

public Double getClassId() {


return classId;
}

public Grade setClassId(Double classId) {


this.classId = classId;
return this;
}

public List<Score> getScores() {


return scores;
}

public Grade setScores(List<Score> scores) {


this.scores = scores;
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,

grade.classId) && Objects


.equals(scores, grade.scores);

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;

public class Score {

private String type;


private Double score;

public String getType() {


return type;
}

public Score setType(String type) {


this.type = type;
return this;
}

public Double getScore() {


return score;
}

public Score setScore(Double score) {


this.score = score;
return this;
}

@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>

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<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

The pom.xml file should contain the following code:


<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.or
g/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mongodb</groupId>
<artifactId>java-quick-start</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<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>3.11.0</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>
</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>

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):

mvn compile exec:java -


Dexec.mainClass="com.mongodb.quickstart.HelloMongoDB"

The result should look like this:

[...]
[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] ------------------------------------------------------------------------


In src/main/java/com/mongodb, create the Connection.java file:

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()));
}
}
}

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Connection"


-Dmongodb.uri="mongodb+srv://username:password@cluster0-
abcde.mongodb.net/test?w=majority"

{"name": "admin", "sizeOnDisk": 303104.0, "empty": false}


{"name": "config", "sizeOnDisk": 147456.0, "empty": false}
{"name": "local", "sizeOnDisk": 5.44731136E8, "empty": false}
{"name": "sample_airbnb", "sizeOnDisk": 5.761024E7, "empty": false}
{"name": "sample_geospatial", "sizeOnDisk": 1384448.0, "empty": false}
{"name": "sample_mflix", "sizeOnDisk": 4.583424E7, "empty": false}
{"name": "sample_supplies", "sizeOnDisk": 1339392.0, "empty": false}
{"name": "sample_training", "sizeOnDisk": 7.4801152E7, "empty": false}
{"name": "sample_weatherdata", "sizeOnDisk": 5103616.0, "empty": false}

Here is the JSON representation of a document in the Mongo Shell.


MongoDB Enterprise Cluster0-shard-0:PRIMARY>


db.grades.findOne({student_id: 0, class_id: 339})
{
"_id" : ObjectId("56d5f7eb604eb380b0d8d8ce"),
"student_id" : 0,
"scores" : [
{
"type" : "exam",
"score" : 78.40446309504266
},
{
"type" : "quiz",
"score" : 73.36224783231339
},
{
"type" : "homework",
"score" : 46.980982486720535
},
{
"type" : "homework",
"score" : 76.67556138656222
}
],
"class_id" : 339
}

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");
}
}
}

Create a BSON Document


Secondly, we need to represent this new student in Java using the Document
class.

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)));

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);
}
}
}

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Create" -


Dmongodb.uri="mongodb+srv://USERNAME:PASSWORD@cluster0-
abcde.mongodb.net/test?w=majority"

And here is the document I extracted from MongoDB Compass.

{
"_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"
}
}]
}

Random rand = new Random();


Document student = new Document("_id", new ObjectId());
student.append("student_id", 10000d)
.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)))
.append("class_id", 1d);

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);
}

List<Document> grades = new ArrayList<>();


for (double classId = 1d; classId <= 10d; classId++) {
grades.add(generateNewGrade(10001d, classId));
}
gradesCollection.insertMany(grades, new InsertManyOptions().ordered(false));


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);
}
}

MongoDB Enterprise Cluster0-shard-0:PRIMARY>


db.grades.findOne({"student_id":10000})
{
"_id" : ObjectId("5daa0e274f52b44cfea94652"),
"student_id" : 10000,
"class_id" : 1,
"scores" : [
{
"type" : "exam",
"score" : 39.25175977753478
},
{
"type" : "quiz",
"score" : 80.2908713167313
},
{
"type" : "homework",
"score" : 63.5444978481843
},
{
"type" : "homework",
"score" : 82.35202261582563
}
]
}


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());
}
}
}

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Read" -


Dmongodb.uri="mongodb+srv://USERNAME:PASSWORD@cluster0-
abcde.mongodb.net/test?w=majority"

The standard output should be:

Student 1: {"_id": {"$oid": "5daa0e274f52b44cfea94652"},


"student_id": 10000.0,
"class_id": 1.0,
"scores": [
{"type": "exam", "score": 39.25175977753478},
{"type": "quiz", "score": 80.2908713167313},
{"type": "homework", "score": 63.5444978481843},
{"type": "homework", "score": 82.35202261582563}
]
}


// without helpers
gradesCollection.find(new Document("student_id", new Document("$gte",
10000)));
// with the Filters.gte() helper
gradesCollection.find(gte("student_id", 10000));

FindIterable<Document> iterable = gradesCollection.find(gte("student_id",


10000));
MongoCursor<Document> cursor = iterable.iterator();
System.out.println("Student list with cursor: ");
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}

Lists
Lists are usually easier to manipulate than iterators, so we can also do this to
retrieve directly an ArrayList<Document>:

List<Document> studentList = gradesCollection.find(gte("student_id",


10000)).into(new ArrayList<>());
System.out.println("Student list with an ArrayList:");
for (Document student : studentList) {
System.out.println(student.toJson());
}

Consumers
We could also use a Consumer which is a functional interface:

Consumer<Document> printConsumer = document ->


System.out.println(document.toJson());
gradesCollection.find(gte("student_id", 10000)).forEach(printConsumer);


Cursors, Sort, Skip, Limit, and Projections
As we saw above with the Iterator example, MongoDB leverages cursors to
iterate through your result set.

List<Document> docs = gradesCollection.find(and(eq("student_id", 10001),


lte("class_id", 5)))
.projection(fields(excludeId(),
include("class_id",
"student_id")))
.sort(descending("class_id"))
.skip(2)
.limit(2)
.into(new ArrayList<>());
System.out.println("Student sorted, skipped, limited and projected: ");
for (Document student : docs) {
System.out.println(student.toJson());
}

Here is the output we get:

{"student_id": 10001.0, "class_id": 3.0}


{"student_id": 10001.0, "class_id": 2.0}

db.grades.createIndex({"student_id": 1, "class_id": -1})


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]"
]
}
}
}
}
}

The Final Code To Read Documents


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;
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());
// find one document with Filters.eq()
Document student2 = gradesCollection.find(eq("student_id", 10000)).first();
System.out.println("Student 2: " + student2.toJson());
// find a list of documents and iterate throw it using an iterator.
FindIterable<Document> iterable = gradesCollection.find(gte("student_id",
10000));
MongoCursor<Document> cursor = iterable.iterator();
System.out.println("Student list with a cursor: ");
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
// find a list of documents and use a List object instead of an iterator
List<Document> studentList = gradesCollection.find(gte("student_id",
10000)).into(new ArrayList<>());
System.out.println("Student list with an ArrayList:");
for (Document student : studentList) {
System.out.println(student.toJson());
}
// find a list of documents and print using a consumer
System.out.println("Student list using a Consumer:");
Consumer<Document> printConsumer = document ->
System.out.println(document.toJson());
gradesCollection.find(gte("student_id", 10000)).forEach(printConsumer);
// find a list of documents with sort, skip, limit and projection
List<Document> docs = gradesCollection.find(and(eq("student_id", 10001),
lte("class_id", 5)))
.projection(fields(excludeId(), include("class_id", "student_id")))
.sort(descending("class_id"))
.skip(2)
.limit(2)
.into(new ArrayList<>());
System.out.println("Student sorted, skipped, limited and projected: ");
for (Document student : docs) {
System.out.println(student.toJson());
}
}
}
}


Update Operations
Update One Document
Let's edit the document with {student_id: 10000}. To achieve this, we will use the
method updateOne.

create a class Update in the com.mongodb.quickstart package with this code:


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);
}
}
}


mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Update" -


Dmongodb.uri="mongodb+srv://USERNAME:PASSWORD@cluster0-
abcde.mongodb.net/test?w=majority"

The standard output should look like this:

=> Updating the doc with {"student_id":10000}. Adding comment.


{
"_id": {
"$oid": "5dd5c1f351f97d4a034109ed"
},
"student_id": 10000.0,
"class_id": 1.0,
"scores": [
{
"type": "exam",
"score": 21.580800815091415
},
{
"type": "quiz",
"score": 87.66967927111044
},
{
"type": "homework",
"score": 96.4060480668003
},
{
"type": "homework",
"score": 75.44966835508427
}
],
"comment": "You should learn MongoDB!"
}
AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}


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

You might also like