Jagadeesh
Jagadeesh

Reputation: 2097

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

Upvotes: 2

Views: 6936

Answers (4)

Codemaker2015
Codemaker2015

Reputation: 15591

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"),
    }
})

Upvotes: 0

vladi_strilets
vladi_strilets

Reputation: 13

One line solution with moment:

const moment = require("moment")

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

Upvotes: 0

Utkarsh Dubey
Utkarsh Dubey

Reputation: 776

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

Upvotes: 3

chirag
chirag

Reputation: 1779

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

Upvotes: 3

Related Questions