【问题标题】:mongoDB Aggregate By Date and another fieldmongoDB 按日期聚合和另一个字段
【发布时间】:2017-06-26 16:33:41
【问题描述】:

我正在尝试按日期字段和报价 id 字段运行聚合。我有以下代码生成每个月查看的所有优惠的总和。

db.useroffers.aggregate(

    {$project: {date: {
        month: {$month: "$viewdate"},
        year: {$year: "$viewdate"},
    }}},
    {$limit: {offer_id: {$in: [101,102,103,104,105,106]}}},
    {$group: {_id: {offer_id: "$offer_id", date: "$date"}, views: {$sum: 1}}}
)

但是,我需要按 $month-$year 分组,并显示查看到有限 offer_ids 的每个报价的总和。

【问题讨论】:

  • 我不确定我是否完全理解您要执行的操作,但在您的 aggregate 通话中,$limit 应该是 $match

标签: node.js mongodb aggregation-framework


【解决方案1】:

使用示例文档会更好地解决问题,但似乎您的某些术语混杂在一起。

首先$project 用于对管道中的文档进行整形。虽然您已将日期的结构更改为您想要的,但您已经省略了您希望稍后在其他管道阶段使用的其他字段。唯一隐式包含的其他字段是_id。所以你需要显式声明你想要的字段。

其次,$limit 仅采用单个数字参数,表示要保留的集合中的文档数。如果您正在测试一个非常大的源并且想要一个子集直到您的整个管道完成,或者在对最终结果进行排序之后您只想返回一定数量的条目时,通常才有意义使用它。

对于您在此处尝试执行的那种 selection,您需要 $match 运算符,您可以按照您尝试 match 的方式使用它一组offer_id 值。

db.useroffers.aggregate(
    // Match first
    {$match: {offer_id: {$in: [101,102,103,104,105,106]}}},

    // Change the document. You could also do this in group
    {$project: {
        date: {
            month: {$month: "$viewdate"},
            year: {$year: "$viewdate"},
        },
        offer_id: 1,
        views: 1
    }},

    // Group by "date" and "offer_id"
    {$group: {
        _id: { date: "$date", offer_id: "$offer_id"},
        views: {$sum: 1}
    }},

    // Nicer output
    {$project: {
        _id: 0,
        date: {$concat: [
            {$substr: ["$_id.date.month", 0, 2]},
            "-",
            {$substr: ["$_id.date.year", 0, 4]}
        ]},
        offer_id: "$_id.offer_id,
        views: 1
    }}
)

【讨论】:

  • 尼尔,感谢您的好评。我想要达到的目标如下:[{01/2013: {101: 16 //this the sum of view for this offer, 102: 8, 103:...}},{02/2013:{101: 4, 102: 7, 103:...}},...]。我尝试了您的代码,但出现“SyntaxError: Unexpected token)”错误。我正在尝试调试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-11
  • 2018-04-25
  • 2013-11-25
  • 2020-11-09
  • 1970-01-01
  • 2019-10-25
相关资源
最近更新 更多