简体   繁体   中英

how to filter last 10 days records from mongoDb?

var require = require('moment');
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();

if(dd<10) {
  dd='0'+dd
} 

if(mm<10) {   
  mm='0'+mm
} 

today = yyyy+'/'+mm+'/'+dd;
console.log(today);
videofiles.find({date:{$lte:'today'}}

Above mention is my code ..The below is my Db values..i do no how to filter last 10 days records from mongodb. I have mentioned the value of filter date as lesser than or equal to today but i really need to filter last 10 days of records and i am new to mongo db and node.js videofiles refers to the name of my collection in mongodb.

"date": "2017/03/10",
"is_deleted": 0,
"filemimeType": "audio/mp3",
"emotionCount": 0,
"originalname": "1489042167918-1489040146195-SampleAudio_0.5mb (1).mp3",
"updatedAt": "2017-03-10T05:54:34.032Z",
"isUserLiked": 0,
"country": "India",
"fileuploadFilename": "1489125273974-1489042167918-1489040146195-SampleAudio_0.5mb (1).mp3",
"_id": "58c23f9a180ac54d758b5fc0",
"likeCount": 0,
"viewed": 0

you can do this for last 10 days records,

videofiles.find(
{
    "date": 
    {
        $gte: (new Date((new Date()).getTime() - (10 * 24 * 60 * 60 * 1000)))
    }
}
).sort({ "date": -1 })

Add this code:

today.setDate(today.getDate() - 10);

after this line:

var today = new Date();

and then replace your line of code:

videofiles.find({date:{$lte:'today'}}

with this line:

db.videofiles.find({"date":{"$gte":'today'}})

One line solution with moment :

const moment = require("moment")

const docs = await Doc.find({
    createdAt: {
        $gte: moment().add(-10, "days"),
    }
})

use find() method and createAt attribute to find the records for last 10 days,

const moment = require("moment")
const docs = await Doc.find({
    createdAt: {
        $gte: moment().add(-10, "days"),
    }
})

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