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:
parent
5bc3c69737
commit
b161aeec27
@ -14,20 +14,14 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embedmongo</groupId>
|
||||
<artifactId>de.flapdoodle.embedmongo</artifactId>
|
||||
<version>${flapdoodle.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongo-java-driver</artifactId>
|
||||
<artifactId>mongodb-driver-sync</artifactId>
|
||||
<version>${mongo.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>dev.morphia.morphia</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<artifactId>morphia-core</artifactId>
|
||||
<version>${morphia.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -42,12 +36,18 @@
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<version>${flapdoodle.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<mongo.version>3.12.1</mongo.version>
|
||||
<flapdoodle.version>1.11</flapdoodle.version>
|
||||
<morphia.version>1.5.3</morphia.version>
|
||||
<mongo.version>4.8.2</mongo.version>
|
||||
<flapdoodle.version>4.4.1</flapdoodle.version>
|
||||
<morphia.version>2.0.0</morphia.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,53 +1,64 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.DBCursor;
|
||||
import com.mongodb.MongoClient;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
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 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
|
||||
mongoClient.getDatabaseNames().forEach(System.out::println);
|
||||
boolean collectionExists = mongoClient.getDatabase("myMongoDb").listCollectionNames()
|
||||
.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
|
||||
database.getCollectionNames().forEach(System.out::println);
|
||||
// create data
|
||||
MongoCollection<Document> collection = database.getCollection("customers");
|
||||
Document document = new Document();
|
||||
document.put("name", "Shubham");
|
||||
document.put("company", "Baeldung");
|
||||
collection.insertOne(document);
|
||||
|
||||
// create data
|
||||
DBCollection collection = database.getCollection("customers");
|
||||
BasicDBObject document = new BasicDBObject();
|
||||
document.put("name", "Shubham");
|
||||
document.put("company", "Baeldung");
|
||||
collection.insert(document);
|
||||
// update data
|
||||
Document query = new Document();
|
||||
query.put("name", "Shubham");
|
||||
Document newDocument = new Document();
|
||||
newDocument.put("name", "John");
|
||||
Document updateObject = new Document();
|
||||
updateObject.put("$set", newDocument);
|
||||
collection.updateOne(query, updateObject);
|
||||
|
||||
// update data
|
||||
BasicDBObject query = new BasicDBObject();
|
||||
query.put("name", "Shubham");
|
||||
BasicDBObject newDocument = new BasicDBObject();
|
||||
newDocument.put("name", "John");
|
||||
BasicDBObject updateObject = new BasicDBObject();
|
||||
updateObject.put("$set", newDocument);
|
||||
collection.update(query, updateObject);
|
||||
// read data
|
||||
Document searchQuery = new Document();
|
||||
searchQuery.put("name", "John");
|
||||
FindIterable<Document> cursor = collection.find(searchQuery);
|
||||
try (final MongoCursor<Document> cursorIterator = cursor.cursor()) {
|
||||
while (cursorIterator.hasNext()) {
|
||||
System.out.println(cursorIterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
// read data
|
||||
BasicDBObject searchQuery = new BasicDBObject();
|
||||
searchQuery.put("name", "John");
|
||||
DBCursor cursor = collection.find(searchQuery);
|
||||
while (cursor.hasNext()) {
|
||||
System.out.println(cursor.next());
|
||||
// delete data
|
||||
Document deleteQuery = new Document();
|
||||
deleteQuery.put("name", "John");
|
||||
collection.deleteOne(deleteQuery);
|
||||
}
|
||||
|
||||
// delete data
|
||||
BasicDBObject deleteQuery = new BasicDBObject();
|
||||
deleteQuery.put("name", "John");
|
||||
collection.remove(deleteQuery);
|
||||
}
|
||||
}
|
||||
|
@ -1,11 +1,9 @@
|
||||
package com.baeldung.bsontojson;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import dev.morphia.annotations.Embedded;
|
||||
import dev.morphia.annotations.Entity;
|
||||
import dev.morphia.annotations.Field;
|
||||
import dev.morphia.annotations.Id;
|
||||
@ -25,7 +23,7 @@ public class Book {
|
||||
@Property
|
||||
private String title;
|
||||
private String author;
|
||||
@Embedded
|
||||
|
||||
private Publisher publisher;
|
||||
@Property("price")
|
||||
private double cost;
|
||||
|
@ -4,8 +4,8 @@ import java.util.ArrayList;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
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;
|
||||
|
||||
@ -18,7 +18,7 @@ public class CollectionExistence {
|
||||
|
||||
public static void setUp() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
}
|
||||
databaseName = "baeldung";
|
||||
testCollectionName = "student";
|
||||
@ -26,9 +26,9 @@ public class CollectionExistence {
|
||||
|
||||
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);
|
||||
|
||||
System.out.println(collection.count());
|
||||
System.out.println(collection.countDocuments());
|
||||
|
||||
}
|
||||
|
||||
|
@ -5,7 +5,8 @@ import java.util.Date;
|
||||
import org.bson.Document;
|
||||
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.MongoDatabase;
|
||||
|
||||
@ -13,7 +14,7 @@ public class RetrieveIdExample {
|
||||
|
||||
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");
|
||||
MongoCollection<Document> collection = database.getCollection("example");
|
||||
|
@ -3,7 +3,8 @@ package com.baeldung.mongo.update;
|
||||
import org.bson.Document;
|
||||
|
||||
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.result.UpdateResult;
|
||||
@ -16,7 +17,7 @@ public class MultipleFieldsExample {
|
||||
// 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");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
|
||||
|
@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
|
||||
|
||||
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.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@ -83,10 +84,9 @@ public class UpdateFields {
|
||||
|
||||
public static void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
database = mongoClient.getDatabase("baeldung");
|
||||
collection = database.getCollection("student");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
|
||||
|
||||
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.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@ -16,19 +17,19 @@ public class UpdateMultipleFields {
|
||||
//
|
||||
// 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");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
//
|
||||
// Update query
|
||||
//
|
||||
|
||||
//
|
||||
// Update query
|
||||
//
|
||||
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.baeldung.morphia.domain;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
@ -25,7 +24,7 @@ public class Book {
|
||||
@Property
|
||||
private String title;
|
||||
private String author;
|
||||
@Embedded
|
||||
|
||||
private Publisher publisher;
|
||||
@Property("price")
|
||||
private double cost;
|
||||
|
@ -10,8 +10,9 @@ import org.bson.Document;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBCollection;
|
||||
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.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@ -45,7 +46,7 @@ public class TagRepository implements Closeable {
|
||||
* Instantiates a new TagRepository by opening the DB connection.
|
||||
*/
|
||||
public TagRepository() {
|
||||
mongoClient = new MongoClient("localhost", 27018);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27018");
|
||||
MongoDatabase database = mongoClient.getDatabase("blog");
|
||||
collection = database.getCollection("posts");
|
||||
}
|
||||
|
@ -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");
|
||||
|
||||
|
@ -43,7 +43,8 @@
|
||||
<module>java-jpa</module> <!-- long running -->
|
||||
<module>java-jpa-2</module> <!-- long running -->
|
||||
<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-3</module> <!-- long running -->
|
||||
<module>java-mongodb-queries</module> <!-- long running -->
|
||||
|
6
pom.xml
6
pom.xml
@ -1014,7 +1014,7 @@
|
||||
<module>spring-5-webflux-2</module>
|
||||
<module>spring-activiti</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-3</module>
|
||||
<module>spring-core-5</module>
|
||||
@ -1034,6 +1034,7 @@
|
||||
<module>tensorflow-java</module>
|
||||
<module>xstream</module>
|
||||
<module>webrtc</module>
|
||||
<module>persistence-modules/java-mongodb</module>
|
||||
<module>messaging-modules/spring-apache-camel</module>
|
||||
</modules>
|
||||
|
||||
@ -1249,7 +1250,7 @@
|
||||
<module>spring-5-webflux-2</module>
|
||||
<module>spring-activiti</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-3</module>
|
||||
<module>spring-core-5</module>
|
||||
@ -1269,6 +1270,7 @@
|
||||
<module>tensorflow-java</module>
|
||||
<module>xstream</module>
|
||||
<module>webrtc</module>
|
||||
<module>persistence-modules/java-mongodb</module>
|
||||
<module>libraries-2</module>
|
||||
<module>messaging-modules/spring-apache-camel</module>
|
||||
</modules>
|
||||
|
Loading…
x
Reference in New Issue
Block a user