Open In App

How to Find Objects Between Two Dates MongoDB

MongoDB is a widely used NoSQL database and One common requirement in database operations is to query for objects within a certain date range. In MongoDB, this can be achieved using comparison operators along with the $and operator.

In this article, We will learn about How to Find objects between two dates MongoDB by understanding some operators as defined in the article with the help of examples and output in detail.



Find Objects between two dates in MongoDB

MongoDB stores data as documents. A Database contains a collection, and a collection contains documents and the documents contain data, the document can be also called an object. Some entries may contain the dates for example sales collection with purchase_date as field and date as value. We can find the objects between two dates using the find() method and using the comparison operators in MongoDB. To find the date we require a first date and last date for the comparison

Syntax:



db.collection.find({
"date": {
$gt: new Date("YYYY-mm-dd"),
$lt: new Date("YYYY-mm-dd")
}
})

Explanation:

Prerequisites

Examples of Find objects between two dates MongoDB

To understand How to Find objects between two dates MongoDB we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called Customer which contains the information shown below:

(
[
{ c_id: 1, pur_item: "Butter", purchase_date: ISODate("2024-03-19") },
{ c_id: 2, pur_item: "Milk", purchase_date: ISODate("2024-03-26") },
{ c_id: 3, pur_item: "Bread", purchase_date: ISODate("2024-04-02") },
{ c_id: 4, pur_item: "Egg", purchase_date: ISODate("2024-04-11") },
{ c_id: 5, pur_item: "tooth_paste", purchase_date: ISODate("2024-04-20") },
{ c_id: 6, pur_item: "Hat", purchase_date: ISODate("2024-04-25") }
]
);

Example 1: Find the object within the 20th March and 10th April

db.Customer.find({
purchase_date: {
$gte: new Date("2024-03-20"),
$lte: new Date("2024-04-10")
}
});

Output:

Find Objects between two dates in MongoDB

Explanantion:

Example 2: Find Objects between two dates in MongoDB using comparison operator

db.Customer.find({
purchase_date: {
$gt: new Date("2024-04-11"),
$lte: new Date("2024-04-30")
}
});

Output:

Find Objects between two dates in MongoDB using comparison operator

Explanation:

Conclusion

Overall, MongoDB offers powerful features for querying objects within a specific date range. By utilizing comparison operators such as $gte, $lte, $gt, and $lt, along with the $and operator, MongoDB allows for precise and efficient retrieval of documents based on date values. Through examples and detailed explanations, this article has demonstrated how to effectively query objects between two dates in MongoDB. Understanding these concepts and operators is crucial for developers working with date-sensitive data in MongoDB databases.


Article Tags :