【问题标题】:How to sort Arrays of Object using aggregation in mongoDB如何在 mongoDB 中使用聚合对对象数组进行排序
【发布时间】:2021-05-30 06:17:08
【问题描述】:

如何使用聚合对dueDate 进行排序?

todos: [
    {
        task: {
            type: String,
            trim: true,
            required: 'Please Enter your Task',
        },
        dueDate: Date,
        dueTime: String,
    },
],

我尝试了这些方法,但没有成功。

db.server.aggregate(
    { $unwind: '$todos' },
    { $sort: { 'todos.dueDate': -1 } },
    { $group: { _id: '$_id', todos: { $push: '$todos' } } },
    { $project: { 'todos.dueDate': '$dueDate' } }
);

db.server.aggregate(
    { $unwind: '$todos' },
    { $sort: { 'todos.dueDate': -1 } },
    { $group: { "_id": "$_id", todos: { $push: '$todos' } } },
);

我无法理解我在聚合中做错了什么。

示例:-

示例输入

{
  _id: 603ba275cc571e2404e0dd1b,
  task: 'task 1',
  dueDate: 2021-02-27T18:30:00.000Z,
  dueTime: ''
},{
  _id: 603ba285cc571e2404e0dd1c,
  task: 'task 2',
  dueDate: 2021-03-30T18:30:00.000Z,
  dueTime: '07:32 PM'
},{
  _id: 603ba290cc571e2404e0dd1d,
  task: 'task 3',
  dueDate: 2021-03-08T18:30:00.000Z,
  dueTime: '07:32 PM'
},{
  _id: 603ba3a7fea412537c295056,
  task: 'task4',
  dueDate: 2021-03-01T18:30:00.000Z,
  dueTime: '07:37 PM'
}

样本输出


{
  _id: 603ba275cc571e2404e0dd1b,
  task: 'task 1',
  dueDate: 2021-02-27T18:30:00.000Z,
  dueTime: ''
},{
  _id: 603ba3a7fea412537c295056,
  task: 'task4',
  dueDate: 2021-03-01T18:30:00.000Z,
  dueTime: '07:37 PM'
},{
  _id: 603ba290cc571e2404e0dd1d,
  task: 'task 3',
  dueDate: 2021-03-08T18:30:00.000Z,
  dueTime: '07:32 PM'
},{
  _id: 603ba285cc571e2404e0dd1c,
  task: 'task 2',
  dueDate: 2021-03-30T18:30:00.000Z,
  dueTime: '07:32 PM'
}

【问题讨论】:

  • 所以你真的不想按日期分组?
  • 不,我只是希望它返回排序后的dueDate
  • 日期以这种格式存储Tue Mar 09 2021 00:00:00 GMT+0530 (India Standard Time)

标签: javascript node.js database mongodb mongoose


【解决方案1】:

如果您的目标是将group 任务元素按其dueDate 分成不同的组,然后对这些组进行排序,您可以执行以下操作:

db.collection.aggregate([
  {
    "$unwind": "$todos"
  },
  {
    $group: {
      _id: "$todos.dueDate",
      todos: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $sort: {
      "_id": -1
    }
  },
  
])

这是 mongoplayground 上的一个工作示例:https://mongoplayground.net/p/n3cfrLvR2WM


在OP编辑问题并澄清预期结果后,可以简化为:

db.collection.aggregate([
  {
    "$unwind": "$todos"
  },
  {
    $sort: {
      "todos.dueDate": 1
    }
  }
])

Mongoplayground:https://mongoplayground.net/p/YVCAiXrJJPv

【讨论】:

  • 查看编辑 .. 请注意,您应该始终在问题中包含预期结果,以便更轻松地为您提供帮助 ..
  • 我不知道为什么,但它现在仍在工作
  • 嗯,它在 mongoplayground 上按预期工作,对吧?或者这不是你想要的?
  • 是的,它在 mongoplayground 上工作,但在我的项目中不起作用:(
  • 请注意,如果您希望记录按升序排序,则需要使用"todos.dueDate": 1。是这个问题吗?
猜你喜欢
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 2019-05-30
  • 2020-01-26
  • 2020-11-16
  • 1970-01-01
相关资源
最近更新 更多