Reputation: 791
I have a query like this:
const data = await this.iveModel
.aggregate([
{
$group: {
_id: { $month: '$createdAt' },
count: { $sum: 1 },
},
},
])
.exec();
It works fine, but I want to limit the result to the current year, so I have added this:
const inicioDeAnio = moment()
.startOf('year')
.toISOString();
const finDeAnio = moment()
.endOf('year')
.toISOString();
const num = await this.iveModel
.aggregate([
{
$match: {
createdAt: {
$gt: inicioDeAnio,
$lt: finDeAnio
}
}
},
{
$group: {
_id: { $month: '$createdAt' },
count: { $sum: 1 },
},
},
])
.exec();
And this always returns an empty array. I do not know what I'm doing wrong.
Upvotes: 0
Views: 413
Reputation: 11975
Your inicioDeAnio
and finDeAnio
variable is just string, if you want to query by date, you need to use ISODate. Something like:
...{
$match: {
createdAt: {
$gt: ISODate(inicioDeAnio),
$lt: ISODate(finDeAnio)
}
}...
Upvotes: 1