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

时间:2020-08-07 12:17:53

标签: json mongodb mongoose aggregation-framework nosql-aggregation

这是我的示例文档:

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

我想从我的文档中获取数据并按DATE排序显示如下:

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

如何显示按DATE排序的数据?预先谢谢你

1 个答案:

答案 0 :(得分:1)

使用以下查询。

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

给您MongoPlayground