【问题标题】:$match in mongoose aggregate querymongoose 聚合查询中的 $match
【发布时间】: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: 
[]

刚开始使用猫鼬,但我没有找到任何参考资料,为什么我会得到这种奇怪的结果?我需要基于年份和月份的计数值。谁能帮我解决这个问题?

提前感谢您的帮助!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我认为问题在于整数/字符串混淆。

    试试这个:

    {$match:{"year": parseInt(year) }},
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2020-09-22
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多