我有一个架构定义为
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)
当我为以下代码的 $match 中的 year 提供默认值时,我得到了所需的输出。
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
}
]
但是如果我传递动态值,我会得到空数组作为输出
let year = 2020;
let result = await Url.aggregate(
[
{$match:{"year":year}},
{
$project:
{
month: { $month: "$date" }
}
},
{
$group : {
_id : "$month",
count : {$sum : 1}
}
}
]
)
output:
[]
刚开始使用猫鼬,我找不到任何参考资料,为什么我会得到这种奇怪的结果?我需要基于年和月的计数值。有人能帮我解决这个问题吗?
提前感谢您的帮助!
答案 0 :(得分:0)
我认为问题在于整数/字符串混淆。
试试这个:
{$match:{"year": parseInt(year) }},