Skip to content

MongoDB with the Java sync driver

Uses mongodb-driver-sync 5.14. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

mongodb://app:secret@mongo.example.com:27017/shop?authSource=admin
mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin

The address comes from the environment variable MONGODB_URI, so switching to MachNoSQL changes configuration only.

Terminal window
export MONGODB_URI='mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin'
mvn -q compile exec:java

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

src/main/java/example/App.java
// Orders example for MongoDB, unchanged on MachNoSQL.
package example;
import static com.mongodb.client.model.Accumulators.sum;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.sort;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Sorts.descending;
import static com.mongodb.client.model.Updates.inc;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import java.util.List;
import org.bson.Document;
public final class App {
public static void main(String[] args) {
try (MongoClient client = MongoClients.create(System.getenv("MONGODB_URI"))) {
MongoCollection<Document> orders = client.getDatabase("shop").getCollection("orders");
orders.deleteMany(new Document());
orders.insertMany(List.of(
new Document("customer", "ada").append("item", "keyboard").append("qty", 1).append("price", 49.0),
new Document("customer", "ada").append("item", "mouse").append("qty", 2).append("price", 19.5),
new Document("customer", "linus").append("item", "monitor").append("qty", 1).append("price", 199.0)));
System.out.println(orders.find(eq("item", "mouse")).first());
orders.updateOne(eq("item", "mouse"), inc("qty", 1));
Document revenue = new Document("$multiply", List.of("$qty", "$price"));
orders.aggregate(List.of(group("$customer", sum("revenue", revenue)), sort(descending("revenue"))))
.forEach(row -> System.out.println(row.toJson()));
}
}
}
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.machnosql</groupId>
<artifactId>mongodb-example</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<exec.mainClass>example.App</exec.mainClass>
</properties>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.14.0</version>
</dependency>
</dependencies>
</project>