Skip to content

Commit b094ba8

Browse files
chrisjaimesChristian Jaimesbipster
authored
BAEL-5363 Mongodb crud by date (#12293)
Created new mongo module, model, mongo client and unit test Co-authored-by: Christian Jaimes <christian.jaimes@oracle> Co-authored-by: bipster <openbip@gmail.com>
1 parent b14f9aa commit b094ba8

6 files changed

Lines changed: 336 additions & 1 deletion

File tree

persistence-modules/java-mongodb-queries/README.md

Whitespace-only changes.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>parent-modules</artifactId>
7+
<groupId>com.baeldung</groupId>
8+
<version>1.0.0-SNAPSHOT</version>
9+
<relativePath>../../pom.xml</relativePath>
10+
</parent>
11+
<modelVersion>4.0.0</modelVersion>
12+
13+
<artifactId>java-mongodb-queries</artifactId>
14+
15+
<dependencies>
16+
<dependency>
17+
<groupId>org.mongodb</groupId>
18+
<artifactId>mongodb-driver-sync</artifactId>
19+
<version>4.6.0</version>
20+
</dependency>
21+
<dependency>
22+
<groupId>org.junit.jupiter</groupId>
23+
<artifactId>junit-jupiter-api</artifactId>
24+
<version>5.8.1</version>
25+
<scope>compile</scope>
26+
</dependency>
27+
</dependencies>
28+
29+
<properties>
30+
<maven.compiler.source>8</maven.compiler.source>
31+
<maven.compiler.target>8</maven.compiler.target>
32+
</properties>
33+
34+
</project>
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
package com.baeldung.mongo.crud;
2+
3+
import com.baeldung.mongo.crud.model.Event;
4+
import com.mongodb.BasicDBObject;
5+
import com.mongodb.BasicDBObjectBuilder;
6+
import com.mongodb.MongoException;
7+
import com.mongodb.client.MongoClient;
8+
import com.mongodb.client.MongoClients;
9+
import com.mongodb.client.MongoCollection;
10+
import com.mongodb.client.MongoDatabase;
11+
import com.mongodb.client.model.UpdateOptions;
12+
import com.mongodb.client.model.Updates;
13+
import com.mongodb.client.result.InsertOneResult;
14+
import com.mongodb.client.result.DeleteResult;
15+
import com.mongodb.client.result.UpdateResult;
16+
import org.bson.BsonValue;
17+
import org.bson.Document;
18+
import org.bson.codecs.configuration.CodecProvider;
19+
import org.bson.codecs.configuration.CodecRegistry;
20+
import org.bson.codecs.pojo.PojoCodecProvider;
21+
import org.bson.conversions.Bson;
22+
23+
import java.time.LocalDate;
24+
import java.time.LocalDateTime;
25+
import java.time.OffsetDateTime;
26+
import java.time.ZoneId;
27+
import java.time.ZoneOffset;
28+
import java.time.ZonedDateTime;
29+
import java.util.ArrayList;
30+
import java.util.List;
31+
32+
import static com.mongodb.client.model.Filters.and;
33+
import static com.mongodb.client.model.Filters.eq;
34+
import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;
35+
import static com.mongodb.client.model.Filters.gte;
36+
import static com.mongodb.client.model.Filters.lt;
37+
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
38+
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
39+
40+
public class CrudClient {
41+
42+
private static String uri = "mongodb://localhost:27017";
43+
private static MongoClient mongoClient = MongoClients.create(uri);
44+
private static MongoDatabase db;
45+
private static MongoCollection<Event> collection;
46+
47+
public static OffsetDateTime offsetDateTime = OffsetDateTime.of(LocalDateTime.of(2022, 6, 4, 11, 0, 0),
48+
ZoneOffset.ofHours(2));
49+
50+
public static Event pianoLessons = new Event(
51+
"Piano lessons",
52+
"Foo Bvld",
53+
LocalDateTime.of(2022, 6, 4, 11, 0, 0));
54+
55+
public static Event soccerGame = new Event(
56+
"Soccer game",
57+
"Bar Avenue",
58+
LocalDateTime.of(2022, 6, 10, 17, 0, 0));
59+
60+
public static Event pianoLessonsTZ = new Event(
61+
"Piano lessons",
62+
"Baz Bvld",
63+
LocalDateTime.of(2022, 12, 31, 12, 0, 0),
64+
ZoneOffset.ofHours(2).toString());
65+
66+
public static LocalDateTime dateQuery = LocalDateTime.of(2022, 6, 10, 17, 0, 0);
67+
public static LocalDateTime dateQueryEventWithTZ = LocalDateTime.of(2022, 12, 31, 12, 0, 0);
68+
69+
public static LocalDateTime from = LocalDateTime.of(2022, 06, 04, 12, 0, 0);
70+
public static LocalDateTime to = LocalDateTime.of(2022, 06, 10, 17, 0, 0);
71+
72+
public static LocalDate updateManyFrom = LocalDate.of(2022, 1, 1);
73+
public static LocalDate updateManyTo = LocalDate.of(2023, 1, 1);
74+
75+
public static LocalDate deleteFrom = LocalDate.of(2022, 1, 1);
76+
public static LocalDate deleteTo = LocalDate.of(2023, 01, 01);
77+
78+
public static void setup() {
79+
CodecProvider codecProvider = PojoCodecProvider.builder().automatic(true).build();
80+
CodecRegistry codecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(codecProvider));
81+
82+
db = mongoClient.getDatabase("calendar").withCodecRegistry(codecRegistry);
83+
collection = db.getCollection("my_events", Event.class);
84+
}
85+
86+
public static void close() {
87+
mongoClient.close();
88+
}
89+
90+
public static BsonValue insertEventsWithDate(Event e) {
91+
try {
92+
InsertOneResult insertResult = collection.insertOne(e);
93+
return insertResult.getInsertedId();
94+
} catch (MongoException me) {
95+
System.err.println("Failed to insert with error: " + me);
96+
throw me;
97+
}
98+
}
99+
100+
public static Event readEventsByDate(LocalDateTime localDateTime) {
101+
try {
102+
Event event = collection
103+
.find(eq("dateTime", localDateTime))
104+
.first();
105+
return event;
106+
} catch (MongoException me) {
107+
System.err.println("Failed to read with error: " + me);
108+
throw me;
109+
}
110+
}
111+
112+
public static List<Event> readEventsByDateRange(LocalDateTime from, LocalDateTime to) {
113+
BasicDBObject object = new BasicDBObject();
114+
object.put("dateTime", BasicDBObjectBuilder
115+
.start("$gte", from)
116+
.add("$lte", to)
117+
.get());
118+
try {
119+
List<Event> list = new ArrayList<Event>(collection.find(object).into(new ArrayList<Event>()));
120+
return list;
121+
} catch (MongoException me) {
122+
System.err.println("Failed to read with error: " + me);
123+
throw me;
124+
}
125+
}
126+
127+
public static LocalDateTime readEventsByDateWithTZ(LocalDateTime localDateTime) {
128+
try {
129+
Event event = collection
130+
.find(eq("dateTime", localDateTime))
131+
.first();
132+
OffsetDateTime offsetDateTime = OffsetDateTime.of(event.dateTime, ZoneOffset.of(pianoLessonsTZ.timeZoneOffset));
133+
ZonedDateTime zoned = offsetDateTime.atZoneSameInstant(ZoneId.of("America/Toronto"));
134+
return zoned.toLocalDateTime();
135+
} catch (MongoException me) {
136+
System.err.println("Failed to read with error: " + me);
137+
throw me;
138+
}
139+
}
140+
141+
public static long updateDateField() {
142+
Document document = new Document().append("title", "Piano lessons");
143+
Bson update = Updates.currentDate("updatedAt");
144+
UpdateOptions options = new UpdateOptions().upsert(false);
145+
try {
146+
UpdateResult result = collection.updateOne(document, update, options);
147+
return result.getModifiedCount();
148+
} catch (MongoException me) {
149+
System.err.println("Failed to update with error: " + me);
150+
throw me;
151+
}
152+
}
153+
154+
public static long updateManyEventsWithDateCriteria(LocalDate updateManyFrom, LocalDate updateManyTo) {
155+
Bson query = and(gte("dateTime", updateManyFrom), lt("dateTime", updateManyTo));
156+
Bson updates = Updates.currentDate("dateTime");
157+
try {
158+
UpdateResult result = collection.updateMany(query, updates);
159+
return result.getModifiedCount();
160+
} catch(MongoException me) {
161+
System.err.println("Failed to replace/update with error: " + me);
162+
throw me;
163+
}
164+
}
165+
166+
public static long deleteEventsByDate(LocalDate from, LocalDate to) {
167+
Bson query = and(gte("dateTime", from), lt("dateTime", to));
168+
try {
169+
DeleteResult result = collection.deleteMany(query);
170+
return result.getDeletedCount();
171+
} catch (MongoException me) {
172+
System.err.println("Failed to delete with error: " + me);
173+
throw me;
174+
}
175+
}
176+
177+
public static void dropDb() {
178+
db.drop();
179+
}
180+
181+
public static void main(String[] args) {
182+
}
183+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.mongo.crud.model;
2+
3+
import java.time.LocalDateTime;
4+
5+
public class Event {
6+
public String title;
7+
public String location;
8+
public LocalDateTime dateTime;
9+
public String timeZoneOffset;
10+
11+
public Event() {}
12+
public Event(String title, String location, LocalDateTime dateTime) {
13+
this.title = title;
14+
this.location = location;
15+
this.dateTime = dateTime;
16+
}
17+
18+
public Event(String title, String location, LocalDateTime dateTime, String timeZoneOffset) {
19+
this.title = title;
20+
this.location = location;
21+
this.dateTime = dateTime;
22+
this.timeZoneOffset = timeZoneOffset;
23+
}
24+
25+
@Override
26+
public String toString() { return "\nEvent: " + title + "\nWhere: " + location + "\nWhen: " + dateTime; }
27+
}
28+
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.baeldung.mongo.crud;
2+
3+
import com.baeldung.mongo.crud.model.Event;
4+
import org.junit.jupiter.api.AfterAll;
5+
import org.junit.jupiter.api.Assertions;
6+
import org.junit.jupiter.api.BeforeAll;
7+
import org.junit.jupiter.api.MethodOrderer;
8+
import org.junit.jupiter.api.Order;
9+
import org.junit.jupiter.api.Test;
10+
import org.junit.jupiter.api.TestMethodOrder;
11+
12+
import java.io.IOException;
13+
import java.util.List;
14+
15+
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
16+
public class CrudClientLiveTest {
17+
18+
@BeforeAll
19+
public static void setup() {
20+
CrudClient.setup();
21+
}
22+
23+
@Test
24+
@Order(1)
25+
public void whenInsertingEventsWithDate_thenCheckForDocument() {
26+
Assertions.assertNotNull(CrudClient.insertEventsWithDate(CrudClient.pianoLessons));
27+
Assertions.assertNotNull(CrudClient.insertEventsWithDate(CrudClient.soccerGame));
28+
}
29+
30+
@Test
31+
@Order(2)
32+
public void whenReadingEventsByDate_thenCheckForReturnedDocument() {
33+
Assertions.assertNotNull(CrudClient.readEventsByDate(CrudClient.dateQuery));
34+
}
35+
36+
@Test
37+
@Order(3)
38+
public void whenReadingEventsByDateRange_thenCheckForReturnedDocument() {
39+
List<Event> events = CrudClient.readEventsByDateRange(CrudClient.from, CrudClient.to);
40+
Assertions.assertNotNull(events);
41+
Assertions.assertEquals(1, events.size());
42+
}
43+
44+
@Test
45+
@Order(5)
46+
public void whenUpdatingEventsDateField_thenCheckUpdatedCount() {
47+
Assertions.assertEquals(1, CrudClient.updateDateField());
48+
}
49+
50+
@Test
51+
@Order(6)
52+
public void whenUpdatingManyEvents_thenCheckUpdatedCount() {
53+
long updates = CrudClient.updateManyEventsWithDateCriteria(CrudClient.updateManyFrom, CrudClient.updateManyTo);
54+
Assertions.assertTrue(1 < updates);
55+
}
56+
57+
@Test
58+
@Order(7)
59+
public void whenDeletingEventsWithDate_thenCheckDeletedCount() {
60+
Assertions.assertEquals(2, CrudClient.deleteEventsByDate(CrudClient.deleteFrom, CrudClient.deleteTo));
61+
}
62+
63+
@Test
64+
@Order(8)
65+
public void whenInsertingEventWithDateAndTimeZone_thenCheckForDocument() {
66+
Assertions.assertNotNull(CrudClient.insertEventsWithDate(CrudClient.pianoLessonsTZ));
67+
}
68+
69+
@Test
70+
@Order(9)
71+
public void whenReadingEventsWithDateAndTimeZone_thenCheckInsertedCount() {
72+
Assertions.assertNotEquals(CrudClient.pianoLessonsTZ.dateTime, CrudClient.readEventsByDateWithTZ(CrudClient.dateQueryEventWithTZ));
73+
}
74+
75+
@Test
76+
@Order(10)
77+
public void whenDeletingEventsWithDateAndTimeZone_thenCheckDeletedCount() {
78+
Assertions.assertEquals(1, CrudClient.deleteEventsByDate(CrudClient.deleteFrom, CrudClient.deleteTo));
79+
}
80+
81+
@AfterAll
82+
public static void close() throws IOException {
83+
CrudClient.dropDb();
84+
CrudClient.close();
85+
}
86+
87+
}

pom.xml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77
<groupId>com.baeldung</groupId>
88
<artifactId>parent-modules</artifactId>
99
<version>1.0.0-SNAPSHOT</version>
10-
<name>parent-modules</name>
10+
<modules>
11+
<module>persistence-modules/java-mongodb-queries</module>
12+
</modules>
13+
<name>parent-modules</name>
1114
<packaging>pom</packaging>
1215

1316
<dependencies>

0 commit comments

Comments
 (0)