Java- MongoDB Date Time query with examples
Today, in this article will cover Java – MongoDB Date Time query with examples.
Using Java code, we will see how to get records using a date filter like ‘greater than’ OR ‘less than’ or get the records between 2 dates.
To achieve the same, We will use the MongoDB Driver package supported in JAVA. We will install the Mongo driver and query MongoDB using supported driver classes.
There are 2 types of Java MongoDB driver packages available.
You can use one of the following drivers for your application to work with MongoDB based on what suits your requirements.
- Java Driver – Used for synchronous Java applications.
- Reactive Streams Driver – used for asynchronous stream processing to use the Reactive Streams API.
We will cover the below aspects in today’s article,
Getting started
Here below is a sample schema or document we shall use for the date range query,
Use MongoDB Java Client Libraries
Please install the Java MongoDB driver package to get support for the MongoClient connection class and properties.
For more details visit- https://mongodb.github.io/mongo-java-driver
Add MongoDB Import statements
Please add below IMPORT namespaces
import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.conversions.Bson;
Additionally, you can add below import statements for filter and timestamp query support
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bson.Document;
import com.mongodb.client.FindIterable;
import static com.mongodb.client.model.Filters.lt;
Connecting to an Atlas Cluster in Java Applications
Using the MongoClient class to define the MongoDB Connection,
MongoClient mongoClient = new MongoClient(
new MongoClientURI(
"mongodb://localhost:27017/"
)
);
MongoDatabase database = mongoClient.getDatabase("Books");
MongoCollection<Document> collection = database.getCollection("Book");
FindIterable<Document> result = collection.find(filter);
Above you need to replace the “Books” database with your DB name.
Also please update the “Book” collection name with your collection name.
Here we will be using the below query to get the documents between two dates in MongoDB Collection.
Java query – Mongo Date greater than query (‘gt’)
Define the date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dateAdded= dateFormat.parse("2023-01-01");
Define the filter
Let’s define the date filter as below,
Document query = new Document("DateAdded", new Document("$gt", dateAdded));
Get the results
MongoCursor<Document> cursor = collection.find(query).iterator();
// Iterating over the results
while (cursor.hasNext()) {
Document document = cursor.next();
System.out.println(document.toJson());
}
Complete sample code,
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.conversions.Bson;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bson.Document;
MongoClient mongoClient = new MongoClient(
new MongoClientURI(
"mongodb://localhost:27017/"
)
);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dateAdded= dateFormat.parse("2023-01-01");
Document query = new Document("DateAdded", new Document("$gt", dateAdded));
MongoDatabase database = mongoClient.getDatabase("Books");
MongoCollection<Document> collection = database.getCollection("Book");
MongoCursor<Document> cursor = collection.find(query).iterator();
// Iterating over the results
while (cursor.hasNext()) {
Document document = cursor.next();
System.out.println(document.toJson());
}
Mongo Atlas UI
The above query produces the same result as indicated below using ATLAS UI,
Java example – Mongo Date less than query (‘lt’)
Let’s define JAVA Mongo Datetime less than query (‘lt’)
# define date for the query
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dateAdded= dateFormat.parse("2023-01-01");
Document query = new Document("DateAdded", new Document("$lt", dateAdded));
MongoDatabase database = mongoClient.getDatabase("Books");
MongoCollection<Document> collection = database.getCollection("Book");
MongoCursor<Document> cursor = collection.find(query).iterator();
Java example – Mongo Date less than and greater than date query
# define date for the query
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date startDateAdded= dateFormat.parse("2023-01-01");
Date endDateAdded= dateFormat.parse("2024-01-01");
# define filter for the query
Document query = new Document("DateAdded",
new Document("$gt", startDateAdded)
.append("$lt", endDateAdded));
MongoDatabase database = mongoClient.getDatabase("Books");
MongoCollection<Document> collection = database.getCollection("Book");
MongoCursor<Document> cursor = collection.find(query).iterator();
For more details on queries where no date field in the schema is available, please visit this article,
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.