jones
jones

Reputation: 1453

MongoDB count of records that are published before 30 days

I have a collection named JobPosting and it has a field named publishDate, what i want to do is to get count of records that are published before last 30 days. What i have tried is:

db.JobPosting.aggregate([
    {$match:{
      "publishDate":{$gt: new Date(ISODate().getTime() - 1000*60*60*24*30)}
    }}, 
    {$project:{
      "publishDate":{$gt: new Date(ISODate().getTime() - 1000*60*60*24*30)
    }}, 
    {$group:{
      _id:publishDate, 
      "count":{$sum:1}
    }}
])

Upvotes: 1

Views: 181

Answers (1)

buræquete
buræquete

Reputation: 14698

You can do just this, no need for aggregation usage;

db.JobPosting.find( { publishDate: { $lt : new Date(ISODate() - (1000*60*60*24*30) ) } } )
             .count()

Get the count of documents in JobPosting where the publishDate field is before today - 30days. Since you want the dates before (today - 30days) point, you have to use $lt. Tested on MongoDB web shell.

Upvotes: 2

Related Questions