【问题标题】:Mongoose group results by year and month猫鼬组年和月的结果
【发布时间】:2016-04-11 21:15:17
【问题描述】:

对于以下架构(伪代码)。

var Post = {
     title: "",
     content: "",
     date: new Date()
}

我想返回按月和年分组的结果,所以像这样,再次伪代码:

 [
   { year: "2016", 
     month: "4", 
     results: [ 
         {_id: "1232", title: "foo", content: "bar", date: "Some date" }, 
         {_id: "1232", title: "foosdas", content: "barsdasda", date: "Some other date" } ] }
 ]

我今天早上一直在尝试使用 Mongoose 进行聚合,按月和年分组就好了,但它不会返回实际的模型对象。

这是我当前的聚合查询

               Post
                .aggregate({
                    $group: {
                        _id : { year: { $year : "$date" }, month: { $month : "$date" }},
                    }
                })
                .exec(function (error, items) {
                    if (error) { return next(error); }

                    console.log(items);
                    res.append("x-count", count);
                    return res.json("Done");
                });

【问题讨论】:

  • 你能把你去的地方和原始文件吗?

标签: javascript node.js mongodb


【解决方案1】:

$group 中使用accumulator 运算符来定义_id 之外的字段。

在这种情况下,您可以使用 $pushROOT 系统变量来累积每个月的文档数组:

Post.aggregate([{
    $group: {
        _id : { year: { $year : "$date" }, month: { $month : "$date" }},
        results: {$push: '$$ROOT'}
    }
}).exec(...

【讨论】:

  • 谢谢!在那之后,我真的在使用猫鼬之前三思而后行。一个基本功能的大变通方法。
【解决方案2】:

你可以试试:

mongoose.model('yourCollection').find({year:'2016',month:'4'},function(err,results){
    //your code here
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-30
    • 2018-08-22
    • 2023-03-26
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    相关资源
    最近更新 更多