每月从mongodb文档中获取数据

时间:2016-10-09 04:07:32

标签: javascript node.js mongodb express mongoose

我有一个用户文档并已创建过,所以我应该在条件中做些什么才能按月获取数据?

createdAt值看起来像这样

2016-10-08T16:21:40.935Z
Account.find({'what to pass here?'}, function(err,response){
        if(!err){
            console.log(response)
        }
    });

2 个答案:

答案 0 :(得分:2)

试着把这个条件......

{"createdAt": {'$gte': new Date('2016-10-01'), '$lt': new Date('2016-10-31')}}

如果您希望仅使用一个月的数字和年份动态生成这两个日期。请输入以下代码。

const month = 10;
const year = 2016;
const fromDate = new Date(year, month, 1);
const toDate = new Date(fromDate.getFullYear(), fromDate.getMonth() + 1, 0);

const condition = {"createdAt": {'$gte': date, '$lte': lastDay)}};

Account.find(condition, function(err, response){
    if (!err){
        console.log(response);
    }
});

答案 1 :(得分:0)

试试这个

Account.find({
  "createdAt": {
    "$lte": "2016-10-08T16:21:40.935Z"
  }
}, function(err, response) {
  if (!err) {
    console.log(response)
  }
});

您还可以定义范围以获取特定数据

Account.find({
  "createdAt": {
     "$gte": "2016-10-06T16:21:40.935Z",
    "$lte": "2016-10-08T16:21:40.935Z"
  }
}, function(err, response) {
  if (!err) {
    console.log(response)
  }
});