Skip to content
This repository was archived by the owner on Sep 18, 2024. It is now read-only.

Commit 6521347

Browse files
committed
Initial commit
1 parent e5bbd16 commit 6521347

File tree

4 files changed

+254
-2
lines changed

4 files changed

+254
-2
lines changed

Dockerfile

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
FROM ubuntu:18.04
2+
3+
ARG DRIVER_VERSION=3.11.1
4+
ARG MONGODB_URI
5+
6+
RUN apt-get update && apt-get install -y \
7+
git \
8+
nano \
9+
sudo \
10+
default-jdk \
11+
maven && \
12+
apt-get clean && \
13+
rm -rf /var/lib/apt/lists/*
14+
15+
RUN export uid=1000 gid=1000 && \
16+
mkdir -p /home/ubuntu && \
17+
echo "ubuntu:x:${uid}:${gid}:Developer,,,:/home/ubuntu:/bin/bash" >> /etc/passwd && \
18+
echo "ubuntu:x:${uid}:" >> /etc/group && \
19+
echo "ubuntu ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/ubuntu && \
20+
chmod 0440 /etc/sudoers.d/ubuntu && \
21+
chown ${uid}:${gid} -R /home/ubuntu
22+
23+
ENV HOME /home/ubuntu
24+
ENV JAVA_HOME /usr/lib/jvm/java-11-openjdk-amd64
25+
ENV DRIVER_VERSION ${DRIVER_VERSION}
26+
ENV MONGODB_URI=${MONGODB_URI}
27+
28+
WORKDIR ${HOME}
29+
30+
RUN mkdir -p ${HOME}/java/src/main/java/com/start
31+
COPY ./java/pom.xml ${HOME}/java/
32+
COPY ./java/src/main/java/com/start/Quickstart.java ${HOME}/java/src/main/java/com/start/
33+
34+
RUN sed -i "s/x.x.x/${DRIVER_VERSION}/g" ${HOME}/java/pom.xml
35+
36+
RUN chown -R ubuntu ${HOME}/java && chmod -R 750 ${HOME}/java
37+
38+
USER ubuntu
39+
40+
CMD ["/bin/bash"]

README.md

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,60 @@
1-
# quickstart-java
2-
Repository to help getting started with MongoDB Java driver connecting to MongoDB Atlas
1+
# Quickstart Java
2+
3+
Repository to help getting started with MongoDB Java driver connecting to MongoDB Atlas.
4+
5+
## Information
6+
7+
This Quickstart project uses [MongoDB Java driver](https://mongodb.github.io/mongo-java-driver/) version 3.11.1 by default. Although you can change the driver version, the provided code example was only tested against the default version of MongoDB driver. There is no guarantee that the code sample will work for all possible versions of the driver.
8+
9+
## Pre-requisites
10+
11+
### Docker
12+
13+
Have Docker running on your machine. You can download and install from: https://docs.docker.com/install/
14+
15+
### MongoDB Atlas
16+
17+
In order to execute the code example, you need to specify `MONGODB_URI` environment variable to connect to a MongoDB cluster. If you don't have any you can create one by signing up [MongoDB Atlas Free-tier M0](https://docs.atlas.mongodb.com/getting-started/).
18+
19+
## Build Steps
20+
21+
1. Build Docker image with a tag name. Within this directory execute:
22+
* To use the default driver version and specify `MONGODB_URI`:
23+
```
24+
docker build . -t start-java --build-arg MONGODB_URI="mongodb+srv://usr:pwd@example.mongodb.net/dbname?retryWrites=true"
25+
```
26+
* To use a different driver version and specify `MONGODB_URI`. For example:
27+
```
28+
docker build . -t start-java --build-arg DRIVER_VERSION=3.10.2 --build-arg MONGODB_URI="mongodb+srv://usr:pwd@example.mongodb.net/dbname?retryWrites=true"
29+
```
30+
This will build a docker image with a tag name `start-java`.
31+
As a result of the build, the example code is compiled for the specified driver version and ready to be executed.
32+
33+
2. Run the Docker image by executing:
34+
```
35+
docker run --tty --interactive --hostname java start-java
36+
```
37+
38+
The command above will run a `start-java` tagged Docker image. Sets the hostname as `java`.
39+
40+
## Execution Steps
41+
42+
1. Run the compiled C# code example by following below steps:
43+
* `cd ~/java`
44+
* `mvn package`
45+
* `java -cp ./target/start-1.0-SNAPSHOT.jar com.start.Quickstart`
46+
47+
### Change driver version from within the Docker environment
48+
49+
You can change the version of `mongo-driver-sync` before code compilation time by modifying the [pom.xml: mongo-java-driver version](java/pom.xml#L11).
50+
51+
From within the docker environment, you can also change the `MONGODB_URI` by changing the environment variable:
52+
53+
```sh
54+
export MONGODB_URI="mongodb+srv://usr:pwd@new.mongodb.net/dbname?retryWrites=true"
55+
```
56+
57+
## Related information
58+
59+
* [MongoDB Java driver QuickStart](https://mongodb.github.io/mongo-java-driver/3.11/driver/getting-started/quick-start/)
60+

java/pom.xml

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<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">
2+
<modelVersion>4.0.0</modelVersion>
3+
<groupId>com.start</groupId>
4+
<artifactId>start</artifactId>
5+
<packaging>jar</packaging>
6+
<version>1.0-SNAPSHOT</version>
7+
<dependencies>
8+
<dependency>
9+
<groupId>org.mongodb</groupId>
10+
<artifactId>mongodb-driver-sync</artifactId>
11+
<version>x.x.x</version>
12+
</dependency>
13+
</dependencies>
14+
<properties>
15+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16+
</properties>
17+
<build>
18+
<plugins>
19+
<plugin>
20+
<groupId>org.apache.maven.plugins</groupId>
21+
<artifactId>maven-compiler-plugin</artifactId>
22+
<version>3.7.0</version>
23+
<configuration>
24+
<source>1.8</source>
25+
<target>1.8</target>
26+
</configuration>
27+
</plugin>
28+
<plugin>
29+
<groupId>org.apache.maven.plugins</groupId>
30+
<artifactId>maven-shade-plugin</artifactId>
31+
<version>3.1.1</version>
32+
<executions>
33+
<execution>
34+
<phase>package</phase>
35+
<goals>
36+
<goal>shade</goal>
37+
</goals>
38+
<configuration>
39+
<transformers>
40+
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
41+
<mainClass>com.start.Quickstart</mainClass>
42+
</transformer>
43+
</transformers>
44+
</configuration>
45+
</execution>
46+
</executions>
47+
</plugin>
48+
</plugins>
49+
</build>
50+
</project>
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package com.start;
2+
3+
import com.mongodb.Block;
4+
import com.mongodb.client.MongoClients;
5+
import com.mongodb.client.MongoClient;
6+
import com.mongodb.client.MongoCollection;
7+
import com.mongodb.client.MongoCursor;
8+
import com.mongodb.client.MongoDatabase;
9+
import com.mongodb.client.model.BulkWriteOptions;
10+
import com.mongodb.client.model.DeleteOneModel;
11+
import com.mongodb.client.model.InsertOneModel;
12+
import com.mongodb.client.model.ReplaceOneModel;
13+
import com.mongodb.client.model.UpdateOneModel;
14+
import com.mongodb.client.model.WriteModel;
15+
import com.mongodb.client.AggregateIterable;
16+
import com.mongodb.client.result.UpdateResult;
17+
import com.mongodb.client.result.DeleteResult;
18+
19+
import org.bson.Document;
20+
21+
import java.util.ArrayList;
22+
import java.util.List;
23+
import static java.util.Arrays.asList;
24+
25+
import static com.mongodb.client.model.Filters.eq;
26+
import static com.mongodb.client.model.Filters.exists;
27+
import static com.mongodb.client.model.Projections.excludeId;
28+
import static com.mongodb.client.model.Sorts.descending;
29+
30+
public class Quickstart {
31+
32+
public static void main(final String[] args) {
33+
String mongoURI = System.getenv("MONGODB_URI");
34+
35+
MongoClient mongoClient = MongoClients.create(mongoURI);
36+
37+
MongoDatabase database = mongoClient.getDatabase("quickstart");
38+
MongoCollection<Document> collection = database.getCollection("java");
39+
40+
collection.drop();
41+
42+
// make a document and insert it
43+
Document doc = new Document("name", "MongoDB")
44+
.append("type", "database")
45+
.append("count", 1)
46+
.append("info", new Document("x", 203).append("y", 102));
47+
collection.insertOne(doc);
48+
Document myDoc = collection.find().first();
49+
System.out.println(myDoc.toJson());
50+
51+
// insert many
52+
List<Document> documents = new ArrayList<Document>();
53+
for (int i = 0; i < 5; i++) {
54+
documents.add(new Document("i", i));
55+
}
56+
collection.insertMany(documents);
57+
System.out.println("total # of documents : " + collection.countDocuments());
58+
59+
// lets get all the documents in the collection and print them out
60+
MongoCursor<Document> cursor = collection.find().iterator();
61+
try {
62+
while (cursor.hasNext()) {
63+
System.out.println(cursor.next().toJson());
64+
}
65+
} finally {
66+
cursor.close();
67+
}
68+
69+
// now use a query to get 1 document out
70+
myDoc = collection.find(eq("i", 3)).first();
71+
System.out.println(myDoc.toJson());
72+
73+
// Sorting
74+
myDoc = collection.find(exists("i")).sort(descending("i")).first();
75+
System.out.println(myDoc.toJson());
76+
77+
// Projection
78+
myDoc = collection.find().projection(excludeId()).first();
79+
System.out.println(myDoc.toJson());
80+
81+
// Update a document
82+
UpdateResult upResult = collection.updateOne(eq("i", 3), new Document("$set", new Document("x", 20)));
83+
System.out.println(upResult.getModifiedCount());
84+
85+
// Delete a document
86+
DeleteResult delResult = collection.deleteOne(eq("i", 3));
87+
System.out.println(delResult.getDeletedCount());
88+
89+
// Aggregation
90+
Document group = Document.parse("{$group:{_id: null, total :{$sum:'$i'}}}");
91+
List<Document> pipeline = asList(group);
92+
93+
AggregateIterable<Document> iterable = collection.aggregate(pipeline);
94+
iterable.forEach(new Block<Document>() {
95+
@Override
96+
public void apply(final Document document) {
97+
System.out.println(document.toJson());
98+
}
99+
});
100+
101+
// release resources
102+
mongoClient.close();
103+
}
104+
}

0 commit comments

Comments
 (0)