簡體   English   中英

如何使用 mongoDB 中的聚合對 Object 的 Arrays 進行排序

[英]How to sort Arrays of Object using aggregation in mongoDB

如何使用聚合對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'
}

樣品 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'
}

如果您的目標是按任務元素的dueDate日期將任務元素group到單獨的組中,然后對這些組進行排序,那么您可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM