Reputation: 631
How can I select the dates from my mongodb for this month only, I have a date:{type:String}
and my format is: mm-dd-yyyy
ex: 09-03-2019
:
Here is my router to get the distinct dates then count them, but not for monthly:
router.get('/blooddonationarea', function(req, res) {
sess=req.session;
Blooddonation.aggregate([{$group: {_id : "$date" , count :{$sum:1}}},{$sort: {_id: 1}}],function(err, date) {
res.json({ success: true, date: date });
});
});
yields to:
[ { _id: '04-11-2019', count6: 1 },
{ _id: '05-21-2019', count6: 1 },
{ _id: '10-11-2019', count6: 3 },
{ _id: '10-22-2019', count6: 1 } ]
My desired output is to display the dates for example where date = month.now()
then it will only show months for 01-dd-yyyy only.
I tried this :
const startOfMonth = moment().startOf('month').format('MM-DD-YYYY')
const endOfMonth = moment().endOf('month').format('MM-DD-YYYY')
Blooddonation.aggregate([
{ "$match": {
"date": { "$gte": startOfMonth, "$lte": endOfMonth }
}},
{ "$group": { "_id": "$date", "count": { "$sum": 1 } } },
{ "$sort": { "_id": 1 } }],function(err, date) {
res.json({ success: true, date: date });
console.log("dates are" + date);
});
});
Upvotes: 2
Views: 128
Reputation: 46481
You can use moment
library to get the desired format and then use $gte
and $lte
operator to get the data for the current month only
const moment = require('moment')
const startOfMonth = moment().startOf('month').format('MM-DD-YYYY')
const endOfMonth = moment().endOf('month').format('MM-DD-YYYY')
Blooddonation.aggregate([
{ "$match": {
"date": { "$gte": startOfMonth, "$lte": endOfMonth }
}}
{ "$group": { "_id": "$date", "count": { "$sum": 1 } } },
{ "$sort": { "_id": 1 } }
])
Upvotes: 3