【发布时间】:2021-07-20 21:33:04
【问题描述】:
我有一个 Schema 定义为
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:
[]
刚开始使用猫鼬,但我没有找到任何参考资料,为什么我会得到这种奇怪的结果?我需要基于年份和月份的计数值。谁能帮我解决这个问题?
提前感谢您的帮助!
【问题讨论】: