[JAVA-11186] Split java-mongodb module
This commit is contained in:
@@ -1,111 +0,0 @@
|
||||
package com.baeldung.aggregation;
|
||||
|
||||
import static com.mongodb.client.model.Aggregates.count;
|
||||
import static com.mongodb.client.model.Aggregates.group;
|
||||
import static com.mongodb.client.model.Aggregates.limit;
|
||||
import static com.mongodb.client.model.Aggregates.match;
|
||||
import static com.mongodb.client.model.Aggregates.out;
|
||||
import static com.mongodb.client.model.Aggregates.project;
|
||||
import static com.mongodb.client.model.Aggregates.sort;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.bson.conversions.Bson;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
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.Accumulators;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import com.mongodb.client.model.Projections;
|
||||
import com.mongodb.client.model.Sorts;
|
||||
|
||||
public class AggregationLiveTest {
|
||||
|
||||
private static final String DATABASE = "world";
|
||||
private static final String COLLECTION = "countries";
|
||||
private static final String DATASET_JSON = "/countrydata.json";
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase database;
|
||||
private static MongoCollection<Document> collection;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpDB() throws IOException {
|
||||
mongoClient = MongoClients.create();
|
||||
database = mongoClient.getDatabase(DATABASE);
|
||||
collection = database.getCollection(COLLECTION);
|
||||
|
||||
collection.drop();
|
||||
|
||||
InputStream is = AggregationLiveTest.class.getResourceAsStream(DATASET_JSON);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
|
||||
reader.lines()
|
||||
.forEach(line -> collection.insertOne(Document.parse(line)));
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCountryCollection_whenEnglishSpeakingCountriesCounted_thenNinetyOne() {
|
||||
Document englishSpeakingCountries = collection.aggregate(Arrays.asList(match(Filters.eq("languages.name", "English")), count()))
|
||||
.first();
|
||||
|
||||
assertEquals(91, englishSpeakingCountries.get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCountryCollection_whenAreaSortedDescending_thenSuccess() {
|
||||
|
||||
collection.aggregate(Arrays.asList(sort(Sorts.descending("area")), limit(7), out("largest_seven")))
|
||||
.toCollection();
|
||||
|
||||
MongoCollection<Document> largestSeven = database.getCollection("largest_seven");
|
||||
|
||||
assertEquals(7, largestSeven.countDocuments());
|
||||
|
||||
Document usa = largestSeven.find(Filters.eq("alpha3Code", "USA"))
|
||||
.first();
|
||||
|
||||
assertNotNull(usa);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCountryCollection_whenCountedRegionWise_thenMaxInAfrica() {
|
||||
Document maxCountriedRegion = collection.aggregate(Arrays.asList(group("$region", Accumulators.sum("tally", 1)), sort(Sorts.descending("tally"))))
|
||||
.first();
|
||||
assertTrue(maxCountriedRegion.containsValue("Africa"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCountryCollection_whenNeighborsCalculated_thenMaxIsFifteenInChina() {
|
||||
Bson borderingCountriesCollection = project(Projections.fields(Projections.excludeId(), Projections.include("name"), Projections.computed("borderingCountries", Projections.computed("$size", "$borders"))));
|
||||
|
||||
int maxValue = collection.aggregate(Arrays.asList(borderingCountriesCollection, group(null, Accumulators.max("max", "$borderingCountries"))))
|
||||
.first()
|
||||
.getInteger("max");
|
||||
|
||||
assertEquals(15, maxValue);
|
||||
|
||||
Document maxNeighboredCountry = collection.aggregate(Arrays.asList(borderingCountriesCollection, match(Filters.eq("borderingCountries", maxValue))))
|
||||
.first();
|
||||
assertTrue(maxNeighboredCountry.containsValue("China"));
|
||||
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUp() {
|
||||
mongoClient.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.existence.field;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import org.bson.Document;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FieldExistenceLiveTest {
|
||||
private MongoClient mongoClient;
|
||||
private MongoDatabase db;
|
||||
private MongoCollection<Document> collection;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient();
|
||||
db = mongoClient.getDatabase("existence");
|
||||
collection = db.getCollection("users");
|
||||
collection.insertOne(Document.parse("{'name':'Ben','surname': 'Big'}"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMongoCollection_whenUsingFilters_thenCheckingForExistingFieldWorks() {
|
||||
Document nameDoc = collection.find(Filters.exists("name")).first();
|
||||
assertNotNull(nameDoc);
|
||||
assertFalse(nameDoc.isEmpty());
|
||||
|
||||
nameDoc = collection.find(Filters.exists("non_existing")).first();
|
||||
assertNull(nameDoc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMongoCollection_whenUsingStandardDocumentQuery_thenCheckingForExistingFieldWorks() {
|
||||
Document query = new Document("name", new BasicDBObject("$exists", true));
|
||||
Document doc = collection.find(query).first();
|
||||
assertNotNull(doc);
|
||||
assertFalse(doc.isEmpty());
|
||||
|
||||
query = new Document("non_existing", new BasicDBObject("$exists", true));
|
||||
doc = collection.find(query).first();
|
||||
assertNull(doc);
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package com.baeldung.geo;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import com.mongodb.client.model.Indexes;
|
||||
import com.mongodb.client.model.geojson.Point;
|
||||
import com.mongodb.client.model.geojson.Polygon;
|
||||
import com.mongodb.client.model.geojson.Position;
|
||||
|
||||
public class MongoGeospatialLiveTest {
|
||||
|
||||
private MongoClient mongoClient;
|
||||
private MongoDatabase db;
|
||||
private MongoCollection<Document> collection;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient();
|
||||
db = mongoClient.getDatabase("myMongoDb");
|
||||
collection = db.getCollection("places");
|
||||
collection.deleteMany(new Document());
|
||||
collection.createIndex(Indexes.geo2dsphere("location"));
|
||||
collection.insertOne(Document.parse("{'name':'Big Ben','location': {'coordinates':[-0.1268194,51.5007292],'type':'Point'}}"));
|
||||
collection.insertOne(Document.parse("{'name':'Hyde Park','location': {'coordinates': [[[-0.159381,51.513126],[-0.189615,51.509928],[-0.187373,51.502442], [-0.153019,51.503464],[-0.159381,51.513126]]],'type':'Polygon'}}"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchNearby_thenFound() {
|
||||
Point currentLoc = new Point(new Position(-0.126821, 51.495885));
|
||||
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 1000.0, 10.0));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFarLocation_whenSearchNearby_thenNotFound() {
|
||||
Point currentLoc = new Point(new Position(-0.5243333, 51.4700223));
|
||||
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 5000.0, 10.0));
|
||||
|
||||
assertNull(result.first());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchWithinCircleSphere_thenFound() {
|
||||
double distanceInRad = 5.0 / 6371;
|
||||
FindIterable<Document> result = collection.find(Filters.geoWithinCenterSphere("location", -0.1435083, 51.4990956, distanceInRad));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchWithinBox_thenFound() {
|
||||
double lowerLeftX = -0.1427638;
|
||||
double lowerLeftY = 51.4991288;
|
||||
double upperRightX = -0.1256209;
|
||||
double upperRightY = 51.5030272;
|
||||
|
||||
FindIterable<Document> result = collection.find(Filters.geoWithinBox("location", lowerLeftX, lowerLeftY, upperRightX, upperRightY));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchWithinPolygon_thenFound() {
|
||||
ArrayList<List<Double>> points = new ArrayList<List<Double>>();
|
||||
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
|
||||
points.add(Arrays.asList(-0.1121, 51.4989));// Lambeth North
|
||||
points.add(Arrays.asList(-0.13, 51.5163));// Tottenham Court Road
|
||||
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
|
||||
FindIterable<Document> result = collection.find(Filters.geoWithinPolygon("location", points));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchUsingIntersect_thenFound() {
|
||||
ArrayList<Position> positions = new ArrayList<Position>();
|
||||
positions.add(new Position(-0.1439, 51.4952));
|
||||
positions.add(new Position(-0.1346, 51.4978));
|
||||
positions.add(new Position(-0.2177, 51.5135));
|
||||
positions.add(new Position(-0.1439, 51.4952));
|
||||
Polygon geometry = new Polygon(positions);
|
||||
FindIterable<Document> result = collection.find(Filters.geoIntersects("location", geometry));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Hyde Park", result.first().get("name"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.baeldung.mongo;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import com.mongodb.client.model.Updates;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
public class PushOperationLiveTest {
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase db;
|
||||
private static MongoCollection<Document> collection;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
db = mongoClient.getDatabase("baeldung");
|
||||
collection = db.getCollection("orders");
|
||||
|
||||
collection.insertOne(
|
||||
Document.parse("{\n" + " \"customerId\": 1023,\n" + " \"orderTimestamp\": NumberLong(\"1646460073000\"),\n" + " \"shippingDestination\": \"336, Street No.1 Pawai Mumbai\",\n" + " \"purchaseOrder\": 1000,\n"
|
||||
+ " \"contactNumber\":\"9898987676\",\n" + " \"items\": [ \n" + " {\n" + " \"itemName\": \"BERGER\",\n" + " \"quantity\": 1,\n" + " \"price\": 500\n" + " },\n"
|
||||
+ " {\n" + " \"itemName\": \"VEG PIZZA\",\n" + " \"quantity\": 1,\n" + " \"price\": 800\n" + " } \n" + " ]\n" + " }"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOrderCollection_whenPushOperationUsingDBObject_thenCheckingForDocument() {
|
||||
|
||||
DBObject listItem = new BasicDBObject("items", new BasicDBObject("itemName", "PIZZA MANIA").append("quantity", 1)
|
||||
.append("price", 800));
|
||||
BasicDBObject searchFilter = new BasicDBObject("customerId", 1023);
|
||||
BasicDBObject updateQuery = new BasicDBObject();
|
||||
updateQuery.append("$push", listItem);
|
||||
UpdateResult updateResult = collection.updateOne(searchFilter, updateQuery);
|
||||
|
||||
Document orderDetail = collection.find(Filters.eq("customerId", 1023))
|
||||
.first();
|
||||
assertNotNull(orderDetail);
|
||||
assertFalse(orderDetail.isEmpty());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOrderCollection_whenPushOperationUsingDocument_thenCheckingForDocument() {
|
||||
|
||||
Document item = new Document().append("itemName", "PIZZA MANIA")
|
||||
.append("quantity", 1)
|
||||
.append("price", 800);
|
||||
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.push("items", item));
|
||||
|
||||
Document orderDetail = collection.find(Filters.eq("customerId", 1023))
|
||||
.first();
|
||||
assertNotNull(orderDetail);
|
||||
assertFalse(orderDetail.isEmpty());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOrderCollection_whenAddToSetOperation_thenCheckingForDocument() {
|
||||
|
||||
Document item = new Document().append("itemName", "PIZZA MANIA")
|
||||
.append("quantity", 1)
|
||||
.append("price", 800);
|
||||
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
|
||||
|
||||
Document orderDetail = collection.find(Filters.eq("customerId", 1023))
|
||||
.first();
|
||||
assertNotNull(orderDetail);
|
||||
assertFalse(orderDetail.isEmpty());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUp() {
|
||||
mongoClient.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
package com.baeldung.ordering.caseinsensitive;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.*;
|
||||
import com.mongodb.client.model.Collation;
|
||||
import com.mongodb.client.model.Projections;
|
||||
import com.mongodb.client.model.Sorts;
|
||||
import org.bson.Document;
|
||||
import org.bson.conversions.Bson;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.containers.MongoDBContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static com.mongodb.client.model.Aggregates.project;
|
||||
import static com.mongodb.client.model.Aggregates.sort;
|
||||
import static com.mongodb.client.model.Sorts.ascending;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@Testcontainers
|
||||
class CaseInsensitiveOrderingLiveTest {
|
||||
|
||||
private static MongoCollection<Document> userCollections;
|
||||
|
||||
@Container
|
||||
private static final MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));
|
||||
|
||||
@BeforeAll
|
||||
private static void setup() {
|
||||
|
||||
MongoClient mongoClient = new MongoClient(mongoDBContainer.getContainerIpAddress(), mongoDBContainer.getMappedPort(27017));
|
||||
MongoDatabase database = mongoClient.getDatabase("test");
|
||||
userCollections = database.getCollection("users");
|
||||
|
||||
List<Document> list = new ArrayList<>();
|
||||
list.add(Document.parse("{'name': 'ben', surname: 'ThisField' }"));
|
||||
list.add(Document.parse("{'name': 'aen', surname: 'Does' }"));
|
||||
list.add(Document.parse("{'name': 'Ben', surname: 'Not' }"));
|
||||
list.add(Document.parse("{'name': 'cen', surname: 'Matter' }"));
|
||||
list.add(Document.parse("{'name': 'Aen', surname: 'Really' }"));
|
||||
list.add(Document.parse("{'name': 'Cen', surname: 'TrustMe' }"));
|
||||
|
||||
userCollections.insertMany(list);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMongoCollection_whenUsingFindWithSort_caseIsConsideredByDefault() {
|
||||
FindIterable<Document> nameDoc = userCollections.find().sort(ascending("name"));
|
||||
MongoCursor<Document> cursor = nameDoc.cursor();
|
||||
|
||||
List<String> expectedNamesOrdering = Arrays.asList("Aen", "Ben", "Cen", "aen", "ben", "cen");
|
||||
List<String> actualNamesOrdering = new ArrayList<>();
|
||||
while (cursor.hasNext()) {
|
||||
Document document = cursor.next();
|
||||
actualNamesOrdering.add(document.get("name").toString());
|
||||
}
|
||||
|
||||
assertEquals(expectedNamesOrdering, actualNamesOrdering);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMongoCollection_whenUsingFindWithSortAndCollation_caseIsNotConsidered() {
|
||||
FindIterable<Document> nameDoc = userCollections.find().sort(ascending("name"))
|
||||
.collation(Collation.builder().locale("en").build());
|
||||
MongoCursor<Document> cursor = nameDoc.cursor();
|
||||
List<String> expectedNamesOrdering = Arrays.asList("aen", "Aen", "ben", "Ben", "cen", "Cen");
|
||||
List<String> actualNamesOrdering = new ArrayList<>();
|
||||
while (cursor.hasNext()) {
|
||||
Document document = cursor.next();
|
||||
actualNamesOrdering.add(document.get("name").toString());
|
||||
}
|
||||
|
||||
assertEquals(expectedNamesOrdering, actualNamesOrdering);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMongoCollection_whenUsingFindWithSortAndAggregate_caseIsNotConsidered() {
|
||||
|
||||
Bson projectBson = project(
|
||||
Projections.fields(
|
||||
Projections.include("name", "surname"),
|
||||
Projections.computed("lowerName", Projections.computed("$toLower", "$name"))));
|
||||
|
||||
AggregateIterable<Document> nameDoc = userCollections.aggregate(
|
||||
Arrays.asList(projectBson,
|
||||
sort(Sorts.ascending("lowerName"))));
|
||||
|
||||
MongoCursor<Document> cursor = nameDoc.cursor();
|
||||
|
||||
List<String> expectedNamesOrdering = Arrays.asList("aen", "Aen", "ben", "Ben", "cen", "Cen");
|
||||
List<String> actualNamesOrdering = new ArrayList<>();
|
||||
while (cursor.hasNext()) {
|
||||
Document document = cursor.next();
|
||||
actualNamesOrdering.add(document.get("name").toString());
|
||||
}
|
||||
|
||||
assertEquals(expectedNamesOrdering, actualNamesOrdering);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user