Reputation: 153
In node.js from mongodb collection, how do I filter documents of a collection based on the date_added
field as previous year, previous week and previous month? The date_added
field is in ISO Date
Format
{
"_id" : ObjectId("574e68e5ac9fbac82489b689"),
"title" : "car",
"price" : 100,
"date_added" : ISODate("2016-06-01T04:47:33.025Z"),
}
Upvotes: 4
Views: 8407
Reputation: 540
the best way is to use moment.js
Do npm install moment
var moment = require ('moment')
function previous_year_artist(req, res, next) {
var dateTimeTofilter = moment().subtract(1, 'year');
var filter = {
"date_added": {
$gte: new Date(dateTimeTofilter._d)
}
};
db.collection.find(
filter
).toArray(function(err, result) {
if (err) return next(err);
res.send(result);
});
}
use year,month, week
as per your requirment
Upvotes: 2
Reputation: 9473
I assume you have a variable in node.js named dateTimeTofilter
var week = 7,
year =365,
month = 31; // this values you need to calculate and then use in query
var dateTimeTofilter = new Date() - week;
var filter = {"date_added": { $lte: dateTimeTofilter }};
// or $gte- depends on time windows
var cursor = db.collection('collectionName').find(filter);
cursor.forEach(
function(doc) {
//process data here
}
Upvotes: 4