从数组文档中检索和显示数据

Retrieve and display data from Array Document

这是我的示例文档:

{
  _id:1,
  name:Dennis,
  tasks:[{
     task:'Drawing',
     dateFinished: Date()
  },{
     task:'Paint',
     dateFinished: Date()
  }]
}

我想从我的文档中获取数据并像这样显示,按日期排序:

_id:1, task:'Drawing', dateFinished:<here is the date >
_id:1, task:'Paint', dateFinished:<here is the date >

如何显示按 DATE 排序的数据?提前谢谢你

使用下面的查询。

  db.Example.aggregate([
  {
    "$unwind": "$tasks"
  },
  {
    "$sort": {
      "tasks.dateFinished": -1
    }
  },
  {
    "$project": {
      "task": "$tasks.task",
      "dateFinished": "$tasks.dateFinished"
    }
  },
  {
    "$project": {
      "tasks": 0
    }
  }
])

这是给你的 MongoPlayground