how to get number of documents which is created today with mongoose? I'm using MEAN stack. I read Mongoose Api Docs but doesn't understand anything :/
By default there is no way.
Documents don't have creation date associated with them unless you explicitly store it in MongoDB.
In other words your Mongoose schema should have something like created
field:
const blogSchema = new Schema({
created: {type: Date, default: Date.now}
});
Then search for matching docs:
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
doc.find({created: {$gte: today}}).exec(callback);
Supposing you have the date field createdAt
in your schema and you would like to get the number of users registered today, you should create a two date object instances to use in your date range query, start
and end
dates.
Your start
date object should hold the current date time hours at 00:00:00.000
(milliseconds precision) and set the hours for today's date to 23:59:59.999
to the end
date variable:
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
Then pass the modified date objects as usual in your MongoDB aggregation pipeline in the $match
operator:
var pipeline = [
{
"$match": {
"createdAt": { "$gte": start, "$lt": end }
}
},
{
"$group": {
"_id": null,
"count": { "$sum": 1 }
}
}
];
Model.aggregate(pipeline, function (err, result){
if (err) throw new Error();
console.log(JSON.stringify(result));
});
If you are using the momentjs library, this can be done by using the startOf()
and endOf()
methods on the moment's current date object, passing the string 'day'
as arguments:
var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With