基于date的node.js mongodbfilter

mongodb集合中的node.js中,如何根据date_added字段过滤前一年,前一周和前一个月的文档? date_added字段采用ISO Date格式

 { "_id" : ObjectId("574e68e5ac9fbac82489b689"), "title" : "car", "price" : 100, "date_added" : ISODate("2016-06-01T04:47:33.025Z"), } 

最好的方法是使用moment.js
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); }); } 

根据您的需求使用year,month, week

我假设你有一个名为dateTimeTofilter node.js中的variables

 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 }