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 check the version of MongoDB?
- How to use watch in MongoDB?
- How to update one document in MongoDB?
- How to update many documents in MongoDB?
- How to use MongoDB queue?
- How to create a many to many relation in MongoDB?
- How to insert new document into MongoDB?
- How to use hint in MongoDB?
- How to work with time series data in MongoDB?
- How to use unwind in MongoDB?
See more codes...