Reputation: 53
How do I convert the field date of type String
to Date
before doing a filter to get all dates greater than the current date? Thanks!
Upvotes: 3
Views: 7276
Reputation: 51125
$toDate
- Convert date string to Date
.$$NOW
- Variable to get current datetime.$expr
- Allow aggregration expression within the query language.db.collection.find({
$expr: {
$gt: [
{
$toDate: "$date"
},
"$$NOW"
]
}
})
Upvotes: 5
Reputation: 6629
data
[
{
_id: 1,
item: "apple",
qty: 5,
order_date: new Date("2018-03-10")
},
{
_id: 2,
item: "pie",
qty: 10,
order_date: new Date("2018-03-12")
},
{
_id: 3,
item: "ice cream",
qty: 2,
price: "4.99",
order_date: "2018-03-05"
},
{
_id: 4,
item: "almonds",
qty: 5,
price: 5,
order_date: "2018-03-05 +10:00"
}
]
$toDate
db.collection.aggregate([
{
$addFields: {
convertedDate: {
$toDate: "$order_date"
}
}
}
])
Upvotes: 1