mongodbHow to filter by date in MongoDB?
MongoDB provides a range of operators to filter documents by date. The most commonly used operators are $gt (greater than), $gte (greater than or equal to), $lt (less than) and $lte (less than or equal to).
For example, to filter documents with a date field createdAt greater than a given date, the following code can be used:
db.collection.find({
createdAt: {
$gt: new Date("2020-01-01")
}
})
This will return all documents with a createdAt field greater than 2020-01-01.
Code explanation
db.collection.find(): This is the MongoDB command to query documents from a collection.createdAt: This is the name of the date field in the documents.$gt: This is the operator used to filter documents with a date field greater than a given date.new Date("2020-01-01"): This is the given date used for comparison.
Helpful links
More of Mongodb
- How to perform a health check for MongoDB?
- How to use watch in MongoDB?
- How to work with time series data in MongoDB?
- How to use unwind in MongoDB?
- How to use transactions in MongoDB?
- How to use MongoDB queue?
- How to implement pagination in MongoDB?
- What is MongoDB default port?
- How to check the version of MongoDB?
- How to check if array is empty in MongoDB?
See more codes...