【问题标题】:Group documents by month in MongoDB在 MongoDB 中按月对文档进行分组
【发布时间】:2017-10-24 21:33:05
【问题描述】:

现在我有一个 Mongoose 查询,看起来像

Collection
  .find( selector )
  .sort( sortCriteria )
  .select( selectCriteria )
  .populate( populateCriteria1 )
  .populate( populateCriteria2 )
  .then( docs => ... )
  .catch( errHandler )

所以我在查询中做了很多工作。

我收藏中的每个文档都有一个日期。我希望返回的文件按月和年分组。所以它应该变成类似

docs = [
  { _id: { year: 2017, month: 4 }, docs: [ ... ] },
  { _id: { year: 2017, month: 5 }, docs: [ ... ] },
  { _id: { year: 2017, month: 6 }, docs: [ ... ] }
]

我猜这是一个简单的.aggregate(),但我不确定我应该在哪里包含它,因为我使用.find() 进行过滤,使用.sort() 进行排序,使用.select() 进行字段选择,并使用@ 填充987654327@.

每个文档都有字段date,所以它可能类似于

Collection
  .find( selector )
  .aggregate([
    { $project: { month: { $month: $date }, year: { $year },
    { $group: { _id: { $month: $date, $year: $date }, docs: { $push: '' } }
  ])

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    不需要'$project',因为你也可以使用$group中的月份方法

    所以你会得到类似的东西:

    $group:{
        _id : { year: { $year: "$date" }, month: { $month: "$date" } },
        docs: { $push: { field1: "$field1", field2: "$field1" } }
        }}
    

    【讨论】:

    • 谢谢,我可以和populate()一起做吗?你写$push: { field1: ...。是否可以只说它应该推送我选择的所有字段?
    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多