1

I have a collection with documents like follows and I want to sort the documents with respect to the highest date value they contain in status array:

[{
  "_id": "1",
  "name": "Tea",
  "status": [
    {
      "state": "a",
      "date": "2019-08-22"
    },
    {
      "state": "b",
      "date": "2019-07-12"
    },
  ],
  "_id": "2",
  "name": "Coffee",
  "status": [
    {
      "state": "c",
      "date": "2019-05-01"
    },
    {
      "state": "b",
      "date": "2019-12-31"
    }
  ]
}]

So, in the example, the values to be used for sorting should be like:

  • Tea: highest status date 2019-08-22 (state: a)
  • Coffee: highest status date 2019-12-31 (state: b)

Any ideas?

1
  • I fail to see the usefulness of an array here. Create flat documents with an index on name. Commented Jul 12, 2019 at 17:16

2 Answers 2

6
db.collection.find().sort({"status.date":-1})

From the docs:

With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than comparison or a descending sort compares the largest element of the arrays.

Sign up to request clarification or add additional context in comments.

Comments

0

To get sorted element with repect to max date inside the array, you need to extract the maximum date from the array which you can easily do with the $max operator.

db.collection.aggregate([
  { "$addFields": {
    "sortDate": { "$max": "$status.date" }
  }},
  { "$sort": { "sortDate": 1 }}
])

2 Comments

This provides both ascending/descending sort based on max value.
If you want the order in descending order with the max date then Alex answer will work for you. Else you can go with this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.