Dhruv Kaushal
Dhruv Kaushal

Reputation: 670

Sort Mongo subArray

[
   {

    "t": "Sample Question",
    "d": "2018-12-23T21:21:03.430Z",
    "aa": [
        {

            "q": 1,
            "n": "5bee73accda38",
            "iU": "5bee73accda38/5c1f3d7341977/1.mp4"
        },
        {

            "q": 4,
            "n": "5bee73accda38",
            "iU": "5bee73accda38/5c1f3d7341977/1.mp4"
        }
    ]
}]

I'm new to Mongo and trying to sort SubArray(Descending) in MongoDB but still unable to achieve sort based on "q" (Descending Order) index in sub-array.

This is what I have tried but got no success

Question.find({}, function(err, question) {

if (err)
  res.send(err); 

}).sort({'d':-1,'aa.q':-1 }).skip(page).limit(10);

Upvotes: 0

Views: 164

Answers (1)

Akrion
Akrion

Reputation: 18515

You can always use $aggregate and inside $unwind, $sort and then $group:

db.collection.aggregate([
  { $unwind: "$aa" },
  { $sort: { "aa.q": -1 }},
  { $group: {
      _id: "$_id",
      "t": { $first: "$t" },
      "d": { $first: "$d" },
      "aa": { $push: "$aa" }
    }
  }
])

See it working here

Upvotes: 1

Related Questions