简体   繁体   中英

get data from mongodb document by month

I have a user document and have createdAt, so what should I do in the condition in order to get the data by month?

the createdAt value look like this

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

Try putting this condition...

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

If you want these two dates to be generated dynamically using just a month number and year. Put the below code.

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);
    }
});

Try this

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

You can also define range to get specific data

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)
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM