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:
Explanantion:
- In the above example w3wiki database contains Customer collection.Customer collection contains 6 documents with c_id ,pur_item, purchase_date as the field.
- We use greater than equal to and less than equal to operator to find the document within the range of 20th March and 10th April.As 2 document lies within the range hence they are returned.
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:
Explanation:
- In the above example w3wiki database contains Customer collection.Customer collection contains 3 documents with c_id ,pur_item, purchase_date as the field.
- We use greater than and less than operator to find the document within the range of 11th April and 30th April.As 2 document lies within the range hence they are returned.
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.