Abhilash Pandey
Abhilash Pandey

Reputation: 11

How to get date difference in mongoDB ? Date should be come in difference of days?

I wants to filter the collection on the basis of subtract expiry date object with current date and which is less than equal to 10 days.

enter image description here

I am using below code but I am getting date difference in millisecond. I want in exact day difference.

db.metaobject.aggregate( 
    { $unwind :'$certifications.expiry_date'},
    {$project:{
            _id:1,name:1,date-Difference: { $divide:[ {$subtract: [ "$certifications.expiry_date",new Date ]},86400000] }
        }
    },
    {$match:{
          dateDifference:{$lte:10}
        }
    }

)

Upvotes: 1

Views: 368

Answers (1)

Daphoque
Daphoque

Reputation: 4678

If its to be used in node, you dont need to compute the difference :

Compute directly the date + 10 in node js then just to the $lte :

var date = new Date();
var date10 = new Date(date.getTime());
date10.setDate(date10.getDate() + 10);

db.metaobject.aggregate( 
{ $unwind :'$certifications.expiry_date'},

{$match:{
      dateDifference:{$lte: new Date(date10).toJSON()}
    }
}

)

Upvotes: 1

Related Questions