JAVA-18264 Update article "A Guide to MongoDB with Java" (#13466)

* JAVA-18264 Update article "A Guide to MongoDB with Java"

* JAVA-18264 Update with suggestion

* JAVA-18264 Additional updates

* JAVA-18264 Format pom.xml

---------

Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
timis1 2023-02-27 12:38:14 +02:00 committed by GitHub
parent 5bc3c69737
commit b161aeec27
20 changed files with 222 additions and 224 deletions

View File

@ -14,20 +14,14 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>de.flapdoodle.embedmongo</groupId>
<artifactId>de.flapdoodle.embedmongo</artifactId>
<version>${flapdoodle.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.mongodb</groupId> <groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId> <artifactId>mongodb-driver-sync</artifactId>
<version>${mongo.version}</version> <version>${mongo.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>dev.morphia.morphia</groupId> <groupId>dev.morphia.morphia</groupId>
<artifactId>core</artifactId> <artifactId>morphia-core</artifactId>
<version>${morphia.version}</version> <version>${morphia.version}</version>
</dependency> </dependency>
<dependency> <dependency>
@ -42,12 +36,18 @@
<version>${testcontainers.version}</version> <version>${testcontainers.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>${flapdoodle.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<mongo.version>3.12.1</mongo.version> <mongo.version>4.8.2</mongo.version>
<flapdoodle.version>1.11</flapdoodle.version> <flapdoodle.version>4.4.1</flapdoodle.version>
<morphia.version>1.5.3</morphia.version> <morphia.version>2.0.0</morphia.version>
</properties> </properties>
</project> </project>

View File

@ -1,53 +1,64 @@
package com.baeldung; package com.baeldung;
import com.mongodb.BasicDBObject; import java.util.ArrayList;
import com.mongodb.DB;
import com.mongodb.DBCollection; import org.bson.Document;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient; import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoExample { public class MongoExample {
public static void main(String[] args) { public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("myMongoDb");
DB database = mongoClient.getDB("myMongoDb"); // print existing databases
mongoClient.listDatabaseNames().forEach(System.out::println);
// print existing databases boolean collectionExists = mongoClient.getDatabase("myMongoDb").listCollectionNames()
mongoClient.getDatabaseNames().forEach(System.out::println); .into(new ArrayList<>()).contains("customers");
if (!collectionExists) {
database.createCollection("customers");
}
database.createCollection("customers", null); // print all collections in customers database
database.listCollectionNames().forEach(System.out::println);
// print all collections in customers database // create data
database.getCollectionNames().forEach(System.out::println); MongoCollection<Document> collection = database.getCollection("customers");
Document document = new Document();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insertOne(document);
// create data // update data
DBCollection collection = database.getCollection("customers"); Document query = new Document();
BasicDBObject document = new BasicDBObject(); query.put("name", "Shubham");
document.put("name", "Shubham"); Document newDocument = new Document();
document.put("company", "Baeldung"); newDocument.put("name", "John");
collection.insert(document); Document updateObject = new Document();
updateObject.put("$set", newDocument);
collection.updateOne(query, updateObject);
// update data // read data
BasicDBObject query = new BasicDBObject(); Document searchQuery = new Document();
query.put("name", "Shubham"); searchQuery.put("name", "John");
BasicDBObject newDocument = new BasicDBObject(); FindIterable<Document> cursor = collection.find(searchQuery);
newDocument.put("name", "John"); try (final MongoCursor<Document> cursorIterator = cursor.cursor()) {
BasicDBObject updateObject = new BasicDBObject(); while (cursorIterator.hasNext()) {
updateObject.put("$set", newDocument); System.out.println(cursorIterator.next());
collection.update(query, updateObject); }
}
// read data // delete data
BasicDBObject searchQuery = new BasicDBObject(); Document deleteQuery = new Document();
searchQuery.put("name", "John"); deleteQuery.put("name", "John");
DBCursor cursor = collection.find(searchQuery); collection.deleteOne(deleteQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
} }
// delete data
BasicDBObject deleteQuery = new BasicDBObject();
deleteQuery.put("name", "John");
collection.remove(deleteQuery);
} }
} }

View File

@ -1,11 +1,9 @@
package com.baeldung.bsontojson; package com.baeldung.bsontojson;
import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import dev.morphia.annotations.Embedded;
import dev.morphia.annotations.Entity; import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Field; import dev.morphia.annotations.Field;
import dev.morphia.annotations.Id; import dev.morphia.annotations.Id;
@ -25,7 +23,7 @@ public class Book {
@Property @Property
private String title; private String title;
private String author; private String author;
@Embedded
private Publisher publisher; private Publisher publisher;
@Property("price") @Property("price")
private double cost; private double cost;

View File

@ -4,8 +4,8 @@ import java.util.ArrayList;
import org.bson.Document; import org.bson.Document;
import com.mongodb.DB; import com.mongodb.client.MongoClient;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
@ -18,7 +18,7 @@ public class CollectionExistence {
public static void setUp() { public static void setUp() {
if (mongoClient == null) { if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017); mongoClient = MongoClients.create("mongodb://localhost:27017");
} }
databaseName = "baeldung"; databaseName = "baeldung";
testCollectionName = "student"; testCollectionName = "student";
@ -26,9 +26,9 @@ public class CollectionExistence {
public static void collectionExistsSolution() { public static void collectionExistsSolution() {
DB db = mongoClient.getDB(databaseName); MongoDatabase db = mongoClient.getDatabase(databaseName);
System.out.println("collectionName " + testCollectionName + db.collectionExists(testCollectionName)); System.out.println("collectionName " + testCollectionName + db.listCollectionNames().into(new ArrayList<>()).contains(testCollectionName));
} }
@ -62,7 +62,7 @@ public class CollectionExistence {
MongoCollection<Document> collection = database.getCollection(testCollectionName); MongoCollection<Document> collection = database.getCollection(testCollectionName);
System.out.println(collection.count()); System.out.println(collection.countDocuments());
} }

View File

@ -5,7 +5,8 @@ import java.util.Date;
import org.bson.Document; import org.bson.Document;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
@ -13,7 +14,7 @@ public class RetrieveIdExample {
public static void main(String[] args) { public static void main(String[] args) {
try ( MongoClient mongoClient = new MongoClient("localhost", 27017) ) { try ( MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017") ) {
MongoDatabase database = mongoClient.getDatabase("myMongoDb"); MongoDatabase database = mongoClient.getDatabase("myMongoDb");
MongoCollection<Document> collection = database.getCollection("example"); MongoCollection<Document> collection = database.getCollection("example");

View File

@ -3,7 +3,8 @@ package com.baeldung.mongo.update;
import org.bson.Document; import org.bson.Document;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult; import com.mongodb.client.result.UpdateResult;
@ -16,7 +17,7 @@ public class MultipleFieldsExample {
// Connect to cluster (default is localhost:27017) // Connect to cluster (default is localhost:27017)
// //
MongoClient mongoClient = new MongoClient("localhost", 27017); MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("baeldung"); MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("employee"); MongoCollection<Document> collection = database.getCollection("employee");

View File

@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
import org.bson.Document; import org.bson.Document;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Filters;
@ -83,10 +84,9 @@ public class UpdateFields {
public static void setup() { public static void setup() {
if (mongoClient == null) { if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017); mongoClient = MongoClients.create("mongodb://localhost:27017");
database = mongoClient.getDatabase("baeldung"); database = mongoClient.getDatabase("baeldung");
collection = database.getCollection("student"); collection = database.getCollection("student");
} }
} }

View File

@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
import org.bson.Document; import org.bson.Document;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Filters;
@ -16,19 +17,19 @@ public class UpdateMultipleFields {
// //
// Connect to cluster // Connect to cluster
// //
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27007");) {
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("employee");
MongoClient mongoClient = new MongoClient("localhost", 27007); //
MongoDatabase database = mongoClient.getDatabase("baeldung"); // Update query
MongoCollection<Document> collection = database.getCollection("employee"); //
// UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
// Update query
//
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager"))); System.out.println("updateResult:- " + updateResult);
System.out.println("updateResult:- " + updateResult.getModifiedCount());
System.out.println("updateResult:- " + updateResult); }
System.out.println("updateResult:- " + updateResult.getModifiedCount());
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.morphia.domain; package com.baeldung.morphia.domain;
import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@ -25,7 +24,7 @@ public class Book {
@Property @Property
private String title; private String title;
private String author; private String author;
@Embedded
private Publisher publisher; private Publisher publisher;
@Property("price") @Property("price")
private double cost; private double cost;

View File

@ -10,8 +10,9 @@ import org.bson.Document;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection; import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable; import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Filters;
@ -45,7 +46,7 @@ public class TagRepository implements Closeable {
* Instantiates a new TagRepository by opening the DB connection. * Instantiates a new TagRepository by opening the DB connection.
*/ */
public TagRepository() { public TagRepository() {
mongoClient = new MongoClient("localhost", 27018); mongoClient = MongoClients.create("mongodb://localhost:27018");
MongoDatabase database = mongoClient.getDatabase("blog"); MongoDatabase database = mongoClient.getDatabase("blog");
collection = database.getCollection("posts"); collection = database.getCollection("posts");
} }

View File

@ -2,71 +2,50 @@ package com.baeldung;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import org.junit.After; import org.bson.Document;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.mongodb.BasicDBObject; import com.mongodb.client.FindIterable;
import com.mongodb.DB; import com.mongodb.client.MongoClient;
import com.mongodb.DBCollection; import com.mongodb.client.MongoClients;
import com.mongodb.DBCursor; import com.mongodb.client.MongoCollection;
import com.mongodb.Mongo; import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import de.flapdoodle.embedmongo.MongoDBRuntime; import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embedmongo.MongodExecutable; import de.flapdoodle.embed.mongo.transitions.Mongod;
import de.flapdoodle.embedmongo.MongodProcess; import de.flapdoodle.embed.mongo.transitions.RunningMongodProcess;
import de.flapdoodle.embedmongo.config.MongodConfig; import de.flapdoodle.reverse.TransitionWalker;
import de.flapdoodle.embedmongo.distribution.Version;
import de.flapdoodle.embedmongo.runtime.Network;
public class AppLiveTest { public class AppLiveTest {
private static final String DB_NAME = "myMongoDb"; private static final String DB_NAME = "myMongoDb";
private MongodExecutable mongodExe;
private MongodProcess mongod;
private Mongo mongo;
private DB db;
private DBCollection collection;
@Before
public void setup() throws Exception {
// Creating Mongodbruntime instance
MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
// Creating MongodbExecutable
mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6()));
// Starting Mongodb
mongod = mongodExe.start();
mongo = new Mongo("localhost", 12345);
// Creating DB
db = mongo.getDB(DB_NAME);
// Creating collection Object and adding values
collection = db.getCollection("customers");
}
@After
public void teardown() throws Exception {
mongod.stop();
mongodExe.cleanup();
}
@Test @Test
public void testAddressPersistance() { public void testAddressPersistance() {
BasicDBObject contact = new BasicDBObject(); try (TransitionWalker.ReachedState<RunningMongodProcess> running = Mongod.instance().start(Version.V6_0_3)) {
contact.put("name", "John"); try (MongoClient mongo = MongoClients.create("mongodb://" + running.current().getServerAddress().getHost() + ":" + running.current().getServerAddress().getPort())) {
contact.put("company", "Baeldung"); // Creating DB
MongoDatabase db = mongo.getDatabase(DB_NAME);
// Inserting document // Creating collection Object and adding values
collection.insert(contact); MongoCollection<Document> collection = db.getCollection("customers");
DBCursor cursorDoc = collection.find();
BasicDBObject contact1 = new BasicDBObject(); Document contact = new Document();
while (cursorDoc.hasNext()) { contact.put("name", "John");
contact1 = (BasicDBObject) cursorDoc.next(); contact.put("company", "Baeldung");
System.out.println(contact1);
// Inserting document
collection.insertOne(contact);
FindIterable<Document> cursorDoc = collection.find();
Document contact1 = new Document();
final MongoCursor<Document> cursor = cursorDoc.cursor();
while (cursor.hasNext()) {
contact1 = cursor.next();
System.out.println(contact1);
}
assertEquals(contact1.get("name"), "John");
}
} }
assertEquals(contact1.get("name"), "John");
} }
} }

View File

@ -1,5 +1,6 @@
package com.baeldung.bsontojson; package com.baeldung.bsontojson;
import static dev.morphia.query.experimental.filters.Filters.eq;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -14,10 +15,12 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import dev.morphia.Datastore; import dev.morphia.Datastore;
import dev.morphia.DeleteOptions;
import dev.morphia.Morphia; import dev.morphia.Morphia;
public class BsonToJsonLiveTest { public class BsonToJsonLiveTest {
@ -27,9 +30,8 @@ public class BsonToJsonLiveTest {
@BeforeClass @BeforeClass
public static void setUp() { public static void setUp() {
Morphia morphia = new Morphia(); datastore = Morphia.createDatastore(MongoClients.create(), DB_NAME);
morphia.mapPackage("com.baeldung.bsontojson"); datastore.getMapper().mapPackage("com.baeldung.bsontojson");
datastore = morphia.createDatastore(new MongoClient(), DB_NAME);
datastore.ensureIndexes(); datastore.ensureIndexes();
datastore.save(new Book() datastore.save(new Book()
@ -44,25 +46,33 @@ public class BsonToJsonLiveTest {
@AfterClass @AfterClass
public static void tearDown() { public static void tearDown() {
datastore.delete(datastore.createQuery(Book.class)); datastore.find(Book.class)
.filter(eq("isbn", "isbn"))
.filter(eq("title", "title"))
.filter(eq("author", "author"))
.filter(eq("cost", "3.95"))
.delete(new DeleteOptions().multi(true));
} }
@Test @Test
public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() {
String json; String json;
try (MongoClient mongoClient = new MongoClient()) { try (MongoClient mongoClient = MongoClients.create()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first(); Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson(); json = bson.toJson(JsonWriterSettings
.builder()
.dateTimeConverter(new JSONDateFormatEpochTimeConverter())
.build());
} }
String expectedJson = "{\"_id\": \"isbn\", " + String expectedJson = "{\"_id\": \"isbn\", " +
"\"className\": \"com.baeldung.bsontojson.Book\", " + "\"_t\": \"Book\", " +
"\"title\": \"title\", " + "\"title\": \"title\", " +
"\"author\": \"author\", " + "\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
"\"name\": \"publisher\"}, " + "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
"\"price\": 3.95, " + "\"price\": 3.95, " +
"\"publishDate\": {\"$date\": 1577898812000}}"; "\"publishDate\": {\"$date\": 1577898812000}}";
@ -71,12 +81,11 @@ public class BsonToJsonLiveTest {
assertEquals(expectedJson, json); assertEquals(expectedJson, json);
} }
@Test @Test
public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() {
String json; String json;
try (MongoClient mongoClient = new MongoClient()) { try (MongoClient mongoClient = MongoClients.create()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first(); Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson(JsonWriterSettings json = bson.toJson(JsonWriterSettings
@ -86,11 +95,11 @@ public class BsonToJsonLiveTest {
} }
String expectedJson = "{\"_id\": \"isbn\", " + String expectedJson = "{\"_id\": \"isbn\", " +
"\"className\": \"com.baeldung.bsontojson.Book\", " + "\"_t\": \"Book\", " +
"\"title\": \"title\", " + "\"title\": \"title\", " +
"\"author\": \"author\", " + "\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
"\"name\": \"publisher\"}, " + "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
"\"price\": 3.95, " + "\"price\": 3.95, " +
"\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}";
@ -103,7 +112,7 @@ public class BsonToJsonLiveTest {
public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() {
String json; String json;
try (MongoClient mongoClient = new MongoClient()) { try (MongoClient mongoClient = MongoClients.create()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first(); Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson(JsonWriterSettings json = bson.toJson(JsonWriterSettings
@ -113,11 +122,11 @@ public class BsonToJsonLiveTest {
} }
String expectedJson = "{\"_id\": \"isbn\", " + String expectedJson = "{\"_id\": \"isbn\", " +
"\"className\": \"com.baeldung.bsontojson.Book\", " + "\"_t\": \"Book\", " +
"\"title\": \"title\", " + "\"title\": \"title\", " +
"\"author\": \"author\", " + "\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
"\"name\": \"publisher\"}, " + "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
"\"price\": 3.95, " + "\"price\": 3.95, " +
"\"publishDate\": \"2020-01-01T17:13:32Z\"}"; "\"publishDate\": \"2020-01-01T17:13:32Z\"}";

View File

@ -0,0 +1,18 @@
package com.baeldung.bsontojson;
import org.bson.json.Converter;
import org.bson.json.StrictJsonWriter;
/**
* Convertor to epoch time
*/
public class JSONDateFormatEpochTimeConverter implements Converter<Long> {
@Override
public void convert(Long value, StrictJsonWriter writer) {
writer.writeStartObject();
writer.writeName("$date");
writer.writeNumber(String.valueOf(value));
writer.writeEndObject();
}
}

View File

@ -8,8 +8,8 @@ import org.bson.Document;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.mongodb.DB; import com.mongodb.client.MongoClient;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
@ -22,7 +22,7 @@ public class CollectionExistenceLiveTest {
@Before @Before
public void setup() { public void setup() {
if (mongoClient == null) { if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017); mongoClient = MongoClients.create("mongodb://localhost:27017");
databaseName = "baeldung"; databaseName = "baeldung";
testCollectionName = "student"; testCollectionName = "student";
@ -58,28 +58,16 @@ public class CollectionExistenceLiveTest {
} }
@Test
public void givenCollectionExists_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
DB db = mongoClient.getDB(databaseName);
Boolean collectionStatus = db.collectionExists(testCollectionName);
Boolean expectedStatus = true;
assertEquals(expectedStatus, collectionStatus);
}
@Test @Test
public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() { public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
MongoDatabase database = mongoClient.getDatabase(databaseName); MongoDatabase database = mongoClient.getDatabase(databaseName);
boolean collectionExists = database.listCollectionNames() boolean collectionExists = database.listCollectionNames()
.into(new ArrayList<String>()) .into(new ArrayList<>())
.contains(testCollectionName); .contains(testCollectionName);
Boolean expectedStatus = true; Boolean expectedStatus = true;
assertEquals(expectedStatus, collectionExists); assertEquals(expectedStatus, collectionExists);
} }
@Test @Test
@ -88,7 +76,7 @@ public class CollectionExistenceLiveTest {
MongoDatabase database = mongoClient.getDatabase(databaseName); MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(testCollectionName); MongoCollection<Document> collection = database.getCollection(testCollectionName);
Boolean collectionExists = collection.count() > 0 ? true : false; Boolean collectionExists = collection.countDocuments() > 0 ? true : false;
Boolean expectedStatus = false; Boolean expectedStatus = false;
assertEquals(expectedStatus, collectionExists); assertEquals(expectedStatus, collectionExists);

View File

@ -2,39 +2,44 @@ package com.baeldung.morphia;
import static dev.morphia.aggregation.Group.grouping; import static dev.morphia.aggregation.Group.grouping;
import static dev.morphia.aggregation.Group.push; import static dev.morphia.aggregation.Group.push;
import static dev.morphia.query.experimental.filters.Filters.eq;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import com.baeldung.morphia.domain.Author; import com.baeldung.morphia.domain.Author;
import com.baeldung.morphia.domain.Book; import com.baeldung.morphia.domain.Book;
import com.baeldung.morphia.domain.Publisher; import com.baeldung.morphia.domain.Publisher;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClients;
import com.mongodb.client.model.ReturnDocument;
import dev.morphia.Datastore; import dev.morphia.Datastore;
import dev.morphia.DeleteOptions;
import dev.morphia.ModifyOptions;
import dev.morphia.Morphia; import dev.morphia.Morphia;
import dev.morphia.query.FindOptions;
import dev.morphia.query.Query; import dev.morphia.query.Query;
import dev.morphia.query.UpdateOperations; import dev.morphia.query.experimental.updates.UpdateOperators;
@Ignore
public class MorphiaIntegrationTest { public class MorphiaIntegrationTest {
private static Datastore datastore; private static Datastore datastore;
private static ObjectId id = new ObjectId(); private static ObjectId id = new ObjectId();
@BeforeClass @BeforeClass
public static void setUp() { public static void setUp() {
Morphia morphia = new Morphia(); datastore = Morphia.createDatastore(MongoClients.create(), "library");
morphia.mapPackage("com.baeldung.morphia"); datastore.getMapper().mapPackage("com.baeldung.morphia");
datastore = morphia.createDatastore(new MongoClient(), "library");
datastore.ensureIndexes(); datastore.ensureIndexes();
} }
@ -47,11 +52,11 @@ public class MorphiaIntegrationTest {
datastore.save(companionBook); datastore.save(companionBook);
datastore.save(book); datastore.save(book);
List<Book> books = datastore.createQuery(Book.class) Query<Book> booksQuery = datastore.find(Book.class)
.field("title") .filter(eq("title", "Learning Java"));
.contains("Learning Java") List<Book> books = StreamSupport
.find() .stream(booksQuery.spliterator(), true)
.toList(); .collect(Collectors.toList());
assertEquals(1, books.size()); assertEquals(1, books.size());
assertEquals(book, books.get(0)); assertEquals(book, books.get(0));
} }
@ -61,19 +66,13 @@ public class MorphiaIntegrationTest {
Publisher publisher = new Publisher(id, "Awsome Publisher"); Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book); datastore.save(book);
Query<Book> query = datastore.createQuery(Book.class)
.field("title") final Book execute = datastore.find(Book.class)
.contains("Learning Java"); .filter(eq("title", "Learning Java"))
UpdateOperations<Book> updates = datastore.createUpdateOperations(Book.class) .modify(UpdateOperators.set("price", 4.95))
.inc("price", 1); .execute(new ModifyOptions().returnDocument(ReturnDocument.AFTER));
datastore.update(query, updates);
List<Book> books = datastore.createQuery(Book.class) assertEquals(4.95, execute.getCost());
.field("title")
.contains("Learning Java")
.find()
.toList();
assertEquals(4.95, books.get(0)
.getCost());
} }
@Test @Test
@ -81,16 +80,12 @@ public class MorphiaIntegrationTest {
Publisher publisher = new Publisher(id, "Awsome Publisher"); Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book); datastore.save(book);
Query<Book> query = datastore.createQuery(Book.class) datastore.find(Book.class)
.field("title") .filter(eq("title", "Learning Java"))
.contains("Learning Java"); .delete(new DeleteOptions().multi(true));
datastore.delete(query); Query<Book> books = datastore.find(Book.class)
List<Book> books = datastore.createQuery(Book.class) .filter(eq("title", "Learning Java"));
.field("title") assertFalse(books.iterator().hasNext());
.contains("Learning Java")
.find()
.toList();
assertEquals(0, books.size());
} }
@Test @Test
@ -107,7 +102,6 @@ public class MorphiaIntegrationTest {
.out(Author.class); .out(Author.class);
assertTrue(authors.hasNext()); assertTrue(authors.hasNext());
} }
@Test @Test
@ -115,17 +109,12 @@ public class MorphiaIntegrationTest {
Publisher publisher = new Publisher(id, "Awsome Publisher"); Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book); datastore.save(book);
List<Book> books = datastore.createQuery(Book.class) List<Book> books = datastore.find(Book.class)
.field("title") .filter(eq("title", "Learning Java"))
.contains("Learning Java") .iterator(new FindOptions().projection().include("title")).toList();
.project("title", true) assertEquals( 1, books.size());
.find() assertEquals("Learning Java", books.get(0).getTitle());
.toList(); assertNull(books.get(0).getAuthor());
assertEquals(books.size(), 1);
assertEquals("Learning Java", books.get(0)
.getTitle());
assertNull(books.get(0)
.getAuthor());
} }
} }

View File

@ -100,9 +100,7 @@ public class TaggingLiveTest {
results.forEach(System.out::println); results.forEach(System.out::println);
Assert.assertEquals(1, results.size()); Assert.assertEquals(1, results.size());
results.forEach(post -> { results.forEach(post -> Assert.assertFalse(post.getTags().contains("MongoDB")));
Assert.assertFalse(post.getTags().contains("MongoDB"));
});
} }
/** /**

View File

@ -8,7 +8,8 @@ import org.bson.Document;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Filters;
@ -27,7 +28,7 @@ public class UpdateFieldLiveTest {
@BeforeClass @BeforeClass
public static void setup() { public static void setup() {
if (mongoClient == null) { if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017); mongoClient = MongoClients.create("mongodb://localhost:27017");
db = mongoClient.getDatabase("baeldung"); db = mongoClient.getDatabase("baeldung");
collection = db.getCollection("student"); collection = db.getCollection("student");

View File

@ -8,7 +8,8 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Filters;
@ -23,7 +24,7 @@ public class UpdateMultipleFieldsLiveTest {
@Before @Before
public void setup() { public void setup() {
if (mongoClient == null) { if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017); mongoClient = MongoClients.create("mongodb://localhost:27017");
db = mongoClient.getDatabase("baeldung"); db = mongoClient.getDatabase("baeldung");
collection = db.getCollection("employee"); collection = db.getCollection("employee");

View File

@ -43,7 +43,8 @@
<module>java-jpa</module> <!-- long running --> <module>java-jpa</module> <!-- long running -->
<module>java-jpa-2</module> <!-- long running --> <module>java-jpa-2</module> <!-- long running -->
<module>java-jpa-3</module> <module>java-jpa-3</module>
<module>java-mongodb</module> <!-- long running --> <!-- enable it when persistence-modules is migrated to JDK9+ -->
<!-- <module>java-mongodb</module>--> <!-- long running -->
<module>java-mongodb-2</module> <!-- long running --> <module>java-mongodb-2</module> <!-- long running -->
<module>java-mongodb-3</module> <!-- long running --> <module>java-mongodb-3</module> <!-- long running -->
<module>java-mongodb-queries</module> <!-- long running --> <module>java-mongodb-queries</module> <!-- long running -->

View File

@ -1014,7 +1014,7 @@
<module>spring-5-webflux-2</module> <module>spring-5-webflux-2</module>
<module>spring-activiti</module> <module>spring-activiti</module>
<module>spring-batch-2</module> <module>spring-batch-2</module>
<module>spring-boot-modules/spring-caching-2</module> <module>spring-boot-modules/spring-caching-2</module>
<module>spring-core-2</module> <module>spring-core-2</module>
<module>spring-core-3</module> <module>spring-core-3</module>
<module>spring-core-5</module> <module>spring-core-5</module>
@ -1034,6 +1034,7 @@
<module>tensorflow-java</module> <module>tensorflow-java</module>
<module>xstream</module> <module>xstream</module>
<module>webrtc</module> <module>webrtc</module>
<module>persistence-modules/java-mongodb</module>
<module>messaging-modules/spring-apache-camel</module> <module>messaging-modules/spring-apache-camel</module>
</modules> </modules>
@ -1249,7 +1250,7 @@
<module>spring-5-webflux-2</module> <module>spring-5-webflux-2</module>
<module>spring-activiti</module> <module>spring-activiti</module>
<module>spring-batch-2</module> <module>spring-batch-2</module>
<module>spring-boot-modules/spring-caching-2</module> <module>spring-boot-modules/spring-caching-2</module>
<module>spring-core-2</module> <module>spring-core-2</module>
<module>spring-core-3</module> <module>spring-core-3</module>
<module>spring-core-5</module> <module>spring-core-5</module>
@ -1269,6 +1270,7 @@
<module>tensorflow-java</module> <module>tensorflow-java</module>
<module>xstream</module> <module>xstream</module>
<module>webrtc</module> <module>webrtc</module>
<module>persistence-modules/java-mongodb</module>
<module>libraries-2</module> <module>libraries-2</module>
<module>messaging-modules/spring-apache-camel</module> <module>messaging-modules/spring-apache-camel</module>
</modules> </modules>