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:
@@ -2,71 +2,50 @@ package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.bson.Document;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.DBCursor;
|
||||
import com.mongodb.Mongo;
|
||||
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;
|
||||
|
||||
import de.flapdoodle.embedmongo.MongoDBRuntime;
|
||||
import de.flapdoodle.embedmongo.MongodExecutable;
|
||||
import de.flapdoodle.embedmongo.MongodProcess;
|
||||
import de.flapdoodle.embedmongo.config.MongodConfig;
|
||||
import de.flapdoodle.embedmongo.distribution.Version;
|
||||
import de.flapdoodle.embedmongo.runtime.Network;
|
||||
import de.flapdoodle.embed.mongo.distribution.Version;
|
||||
import de.flapdoodle.embed.mongo.transitions.Mongod;
|
||||
import de.flapdoodle.embed.mongo.transitions.RunningMongodProcess;
|
||||
import de.flapdoodle.reverse.TransitionWalker;
|
||||
|
||||
public class AppLiveTest {
|
||||
|
||||
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
|
||||
public void testAddressPersistance() {
|
||||
BasicDBObject contact = new BasicDBObject();
|
||||
contact.put("name", "John");
|
||||
contact.put("company", "Baeldung");
|
||||
try (TransitionWalker.ReachedState<RunningMongodProcess> running = Mongod.instance().start(Version.V6_0_3)) {
|
||||
try (MongoClient mongo = MongoClients.create("mongodb://" + running.current().getServerAddress().getHost() + ":" + running.current().getServerAddress().getPort())) {
|
||||
// Creating DB
|
||||
MongoDatabase db = mongo.getDatabase(DB_NAME);
|
||||
|
||||
// Inserting document
|
||||
collection.insert(contact);
|
||||
DBCursor cursorDoc = collection.find();
|
||||
BasicDBObject contact1 = new BasicDBObject();
|
||||
while (cursorDoc.hasNext()) {
|
||||
contact1 = (BasicDBObject) cursorDoc.next();
|
||||
System.out.println(contact1);
|
||||
// Creating collection Object and adding values
|
||||
MongoCollection<Document> collection = db.getCollection("customers");
|
||||
|
||||
Document contact = new Document();
|
||||
contact.put("name", "John");
|
||||
contact.put("company", "Baeldung");
|
||||
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.bsontojson;
|
||||
|
||||
import static dev.morphia.query.experimental.filters.Filters.eq;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@@ -14,10 +15,12 @@ import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
import dev.morphia.Datastore;
|
||||
import dev.morphia.DeleteOptions;
|
||||
import dev.morphia.Morphia;
|
||||
|
||||
public class BsonToJsonLiveTest {
|
||||
@@ -27,9 +30,8 @@ public class BsonToJsonLiveTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Morphia morphia = new Morphia();
|
||||
morphia.mapPackage("com.baeldung.bsontojson");
|
||||
datastore = morphia.createDatastore(new MongoClient(), DB_NAME);
|
||||
datastore = Morphia.createDatastore(MongoClients.create(), DB_NAME);
|
||||
datastore.getMapper().mapPackage("com.baeldung.bsontojson");
|
||||
datastore.ensureIndexes();
|
||||
|
||||
datastore.save(new Book()
|
||||
@@ -44,25 +46,33 @@ public class BsonToJsonLiveTest {
|
||||
|
||||
@AfterClass
|
||||
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
|
||||
public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() {
|
||||
|
||||
String json;
|
||||
try (MongoClient mongoClient = new MongoClient()) {
|
||||
try (MongoClient mongoClient = MongoClients.create()) {
|
||||
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
|
||||
Document bson = mongoDatabase.getCollection("Books").find().first();
|
||||
json = bson.toJson();
|
||||
json = bson.toJson(JsonWriterSettings
|
||||
.builder()
|
||||
.dateTimeConverter(new JSONDateFormatEpochTimeConverter())
|
||||
.build());
|
||||
}
|
||||
|
||||
String expectedJson = "{\"_id\": \"isbn\", " +
|
||||
"\"className\": \"com.baeldung.bsontojson.Book\", " +
|
||||
"\"_t\": \"Book\", " +
|
||||
"\"title\": \"title\", " +
|
||||
"\"author\": \"author\", " +
|
||||
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
|
||||
"\"name\": \"publisher\"}, " +
|
||||
"\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
|
||||
"\"price\": 3.95, " +
|
||||
"\"publishDate\": {\"$date\": 1577898812000}}";
|
||||
|
||||
@@ -71,12 +81,11 @@ public class BsonToJsonLiveTest {
|
||||
assertEquals(expectedJson, json);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() {
|
||||
|
||||
String json;
|
||||
try (MongoClient mongoClient = new MongoClient()) {
|
||||
try (MongoClient mongoClient = MongoClients.create()) {
|
||||
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
|
||||
Document bson = mongoDatabase.getCollection("Books").find().first();
|
||||
json = bson.toJson(JsonWriterSettings
|
||||
@@ -86,11 +95,11 @@ public class BsonToJsonLiveTest {
|
||||
}
|
||||
|
||||
String expectedJson = "{\"_id\": \"isbn\", " +
|
||||
"\"className\": \"com.baeldung.bsontojson.Book\", " +
|
||||
"\"_t\": \"Book\", " +
|
||||
"\"title\": \"title\", " +
|
||||
"\"author\": \"author\", " +
|
||||
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
|
||||
"\"name\": \"publisher\"}, " +
|
||||
"\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
|
||||
"\"price\": 3.95, " +
|
||||
"\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}";
|
||||
|
||||
@@ -103,7 +112,7 @@ public class BsonToJsonLiveTest {
|
||||
public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() {
|
||||
|
||||
String json;
|
||||
try (MongoClient mongoClient = new MongoClient()) {
|
||||
try (MongoClient mongoClient = MongoClients.create()) {
|
||||
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
|
||||
Document bson = mongoDatabase.getCollection("Books").find().first();
|
||||
json = bson.toJson(JsonWriterSettings
|
||||
@@ -113,11 +122,11 @@ public class BsonToJsonLiveTest {
|
||||
}
|
||||
|
||||
String expectedJson = "{\"_id\": \"isbn\", " +
|
||||
"\"className\": \"com.baeldung.bsontojson.Book\", " +
|
||||
"\"_t\": \"Book\", " +
|
||||
"\"title\": \"title\", " +
|
||||
"\"author\": \"author\", " +
|
||||
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
|
||||
"\"name\": \"publisher\"}, " +
|
||||
"\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
|
||||
"\"price\": 3.95, " +
|
||||
"\"publishDate\": \"2020-01-01T17:13:32Z\"}";
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ import org.bson.Document;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
@@ -22,7 +22,7 @@ public class CollectionExistenceLiveTest {
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
databaseName = "baeldung";
|
||||
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
|
||||
public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
boolean collectionExists = database.listCollectionNames()
|
||||
.into(new ArrayList<String>())
|
||||
.into(new ArrayList<>())
|
||||
.contains(testCollectionName);
|
||||
|
||||
Boolean expectedStatus = true;
|
||||
assertEquals(expectedStatus, collectionExists);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -88,7 +76,7 @@ public class CollectionExistenceLiveTest {
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
|
||||
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||
Boolean collectionExists = collection.count() > 0 ? true : false;
|
||||
Boolean collectionExists = collection.countDocuments() > 0 ? true : false;
|
||||
|
||||
Boolean expectedStatus = false;
|
||||
assertEquals(expectedStatus, collectionExists);
|
||||
|
||||
@@ -2,39 +2,44 @@ package com.baeldung.morphia;
|
||||
|
||||
import static dev.morphia.aggregation.Group.grouping;
|
||||
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.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.bson.types.ObjectId;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.morphia.domain.Author;
|
||||
import com.baeldung.morphia.domain.Book;
|
||||
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.DeleteOptions;
|
||||
import dev.morphia.ModifyOptions;
|
||||
import dev.morphia.Morphia;
|
||||
import dev.morphia.query.FindOptions;
|
||||
import dev.morphia.query.Query;
|
||||
import dev.morphia.query.UpdateOperations;
|
||||
import dev.morphia.query.experimental.updates.UpdateOperators;
|
||||
|
||||
@Ignore
|
||||
public class MorphiaIntegrationTest {
|
||||
|
||||
private static Datastore datastore;
|
||||
private static ObjectId id = new ObjectId();
|
||||
|
||||
@BeforeClass
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Morphia morphia = new Morphia();
|
||||
morphia.mapPackage("com.baeldung.morphia");
|
||||
datastore = morphia.createDatastore(new MongoClient(), "library");
|
||||
datastore = Morphia.createDatastore(MongoClients.create(), "library");
|
||||
datastore.getMapper().mapPackage("com.baeldung.morphia");
|
||||
datastore.ensureIndexes();
|
||||
}
|
||||
|
||||
@@ -47,11 +52,11 @@ public class MorphiaIntegrationTest {
|
||||
datastore.save(companionBook);
|
||||
datastore.save(book);
|
||||
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
Query<Book> booksQuery = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"));
|
||||
List<Book> books = StreamSupport
|
||||
.stream(booksQuery.spliterator(), true)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(1, books.size());
|
||||
assertEquals(book, books.get(0));
|
||||
}
|
||||
@@ -61,19 +66,13 @@ public class MorphiaIntegrationTest {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
Query<Book> query = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java");
|
||||
UpdateOperations<Book> updates = datastore.createUpdateOperations(Book.class)
|
||||
.inc("price", 1);
|
||||
datastore.update(query, updates);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(4.95, books.get(0)
|
||||
.getCost());
|
||||
|
||||
final Book execute = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"))
|
||||
.modify(UpdateOperators.set("price", 4.95))
|
||||
.execute(new ModifyOptions().returnDocument(ReturnDocument.AFTER));
|
||||
|
||||
assertEquals(4.95, execute.getCost());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -81,16 +80,12 @@ public class MorphiaIntegrationTest {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
Query<Book> query = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java");
|
||||
datastore.delete(query);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(0, books.size());
|
||||
datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"))
|
||||
.delete(new DeleteOptions().multi(true));
|
||||
Query<Book> books = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"));
|
||||
assertFalse(books.iterator().hasNext());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -107,7 +102,6 @@ public class MorphiaIntegrationTest {
|
||||
.out(Author.class);
|
||||
|
||||
assertTrue(authors.hasNext());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -115,17 +109,12 @@ public class MorphiaIntegrationTest {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.project("title", true)
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(books.size(), 1);
|
||||
assertEquals("Learning Java", books.get(0)
|
||||
.getTitle());
|
||||
assertNull(books.get(0)
|
||||
.getAuthor());
|
||||
List<Book> books = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"))
|
||||
.iterator(new FindOptions().projection().include("title")).toList();
|
||||
assertEquals( 1, books.size());
|
||||
assertEquals("Learning Java", books.get(0).getTitle());
|
||||
assertNull(books.get(0).getAuthor());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -100,9 +100,7 @@ public class TaggingLiveTest {
|
||||
results.forEach(System.out::println);
|
||||
|
||||
Assert.assertEquals(1, results.size());
|
||||
results.forEach(post -> {
|
||||
Assert.assertFalse(post.getTags().contains("MongoDB"));
|
||||
});
|
||||
results.forEach(post -> Assert.assertFalse(post.getTags().contains("MongoDB")));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,8 @@ import org.bson.Document;
|
||||
import org.junit.BeforeClass;
|
||||
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.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@@ -27,7 +28,7 @@ public class UpdateFieldLiveTest {
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
db = mongoClient.getDatabase("baeldung");
|
||||
collection = db.getCollection("student");
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
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.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@@ -23,7 +24,7 @@ public class UpdateMultipleFieldsLiveTest {
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
db = mongoClient.getDatabase("baeldung");
|
||||
collection = db.getCollection("employee");
|
||||
|
||||
|
||||
Reference in New Issue
Block a user