简体   繁体   中英

How to sort Arrays of Object using aggregation in mongoDB

How can I sort dueDate using aggregate?

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

I tried these things but it didn't work.

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

And

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

I am not able to understand what I am doing wrong in the aggregation.

Example:-

Sample Input

{
  _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'
}

Sample Output


{
  _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'
}

If your goal is to group the tasks elements into separate groups by their dueDate and then sort those groups, here's what you can do:

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

Here's a working example on mongoplayground: https://mongoplayground.net/p/n3cfrLvR2WM


After OP edited the question and clarified what the expceted result is, this can be simplified to:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM