【问题标题】:Mongoose aggregation not sorting dates猫鼬聚合不排序日期
【发布时间】:2015-07-27 06:30:42
【问题描述】:

谁能帮我理解为什么这个聚合查询没有按他们的created_at 日期对结果进行排序?

User.aggregate([
 // Get only records created in the last 30 days
 { $match: {
  "created_at":{ $gt: new Date(today.getTime() - 1000*60*60*24*30) }
 }},
 //Sort the results by signup date
 { $sort : {
  "created_at" : -1 }
 },
 // Get the year, month and day from the createdTimeStamp
 { $project: {
  "year":{ $year:"$created_at" },
  "month":{ $month:"$created_at" },
  "day": { $dayOfMonth:"$created_at" }
 }},
 // Group by year, month and day and get the count
 { $group: {
  _id:{
   year:"$year",
   month:"$month",
   day:"$day"
  },
  "count":{
   $sum:1
  }
 }}
])

【问题讨论】:

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


    【解决方案1】:

    为什么这个聚合查询没有按 created_at 日期对结果进行排序?

    无法保证$group 保持稳定(即:尽可能维持秩序)。

    因此,如果您需要按特定顺序获取结果,则应使用$sort 步骤作为管道的最后一步。类似的东西(未经测试):

    User.aggregate([
     // Get only records created in the last 30 days
     { $match: {
      "created_at":{ $gt: new Date(today.getTime() - 1000*60*60*24*30) }
     }},
     // Get the year, month and day from the createdTimeStamp
     { $project: {
      "year":{ $year:"$created_at" },
      "month":{ $month:"$created_at" },
      "day": { $dayOfMonth:"$created_at" }
     }},
     // Group by year, month and day and get the count
     { $group: {
      _id:{
       year:"$year",
       month:"$month",
       day:"$day"
      },
      "count":{
       $sum:1
      }
     }},
    
     //Sort the results by year-month-day of signup date
     { $sort : {
      "year" : -1,
      "month": -1,
      "day": -1 }
     }
    ])
    

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多