0

This is my example document :

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

I want to get the data from my document and display it like this, sorted by DATE :

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

How can I display this data sorted by DATE ? Thank you in advance

Kins
  • 547
  • 1
  • 5
  • 22
Dennis
  • 3
  • 1

1 Answers1

1

Use the below query.

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

Here is MongoPlayground for you.

RLD
  • 1,867
  • 3
  • 15
  • 20