Reputation: 2315
I need to query the data between two dates.
I was pushing data into mongo where dates are in the format : 13-10-2015 15:08:22
Is there a way to do it?
Can't i tell mongo to compare these as dates with format explicilty mentioned
Upvotes: 1
Views: 8021
Reputation: 1
let today = new Date();
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
{
$match: {
createdAt: {
$gte: sevenDaysAgo,
$lte: today,
},
},
},
Upvotes: 0
Reputation: 377
You can use aggregate function in mongodb.
You can get dates using this :
let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15);
[Here 15 is days. It will subtract 15 days from current date].
TableName.aggregate([
{
"$match":
{
"Date":
{
"$lte": todayDate,
"$gte": beforeDate
}
}
}
])
Upvotes: 1
Reputation: 2601
You can use the generic $gte
and $lte
query modifiers when dealing with Dates in mongo
{ $gte: startDate, $lte: endDate }
should work just fine (where endDate
and startDate
are Javascript Date
objects)
Upvotes: 5