Personally, I prefer to avoid usage of client-side javascript processing / 3rd party library like moment.js to avoid inconsistency of timezone processing between client side and server side.
- range-based query
db.collection.find({
"createdAt": {
$gte: ISODate("2012-01-12T00:00:00Z"),
$lt: ISODate("2012-01-13T00:00:00Z")
}
})
- constructed date range with
$dateFromParts$dateFromParts
db.collection.find({
$expr: {
$gte: [
"$createdAt",
{
"$dateFromParts": {
"year": 2012,
"month": 1,
"day": 12
}
}
]
}
})
- get range with date difference by
$dateSubtract(example is 15 years before current date)
db.collection.find({
$expr: {
$gte: [
"$createdAt",
{
"$dateSubtract": {
"startDate": "$$NOW",
"unit": "year",
"amount": 15
}
}
]
}
})