I have a Schema defined as
const mongoose = require('mongoose');
const urlSchema = new mongoose.Schema({
longURL : {
type : String,
required : true,
},
shortUrl: {
type : String
},
clicks : {
type : Number,
default : 0
},
date: {type: Date, default: new Date()},
year : {
type : Number
}
})
module.exports = mongoose.model('Url',urlSchema)
When I give default value for year in $match for the below code, I'm getting desired output.
let result = await Url.aggregate(
[
{$match:{"year":2020}},
{
$project:
{
month: { $month: "$date" }
}
},
{
$group : {
_id : "$month",
count : {$sum : 1}
}
}
]
)
output :
[
{
"_id": 1, // 1 - represent Jan
"count": 8
},
{
"_id: : 7, // 7 - represent Jul
"count: : 5
}
]
But if I pass dynamic values, I'm getting empty array as output
let year = 2020;
let result = await Url.aggregate(
[
{$match:{"year":year}},
{
$project:
{
month: { $month: "$date" }
}
},
{
$group : {
_id : "$month",
count : {$sum : 1}
}
}
]
)
output:
[]
Just started on working with mongoose and I don't find any reference why I'm getting this kind of weird result? I need count values based on year and month. Can anyone help me out of this?
Thanks for the help in advance!
I think the problem is with the integer/string confussion.
Try this:
{$match:{"year": parseInt(year) }},