0

My MongoDB document structure:

 _id:ObjectId("12345")
    hai:Array
    0:Object
    designation:"software"
    1:Object
    designation:"hardware"
    2:Object
    designation:"Core"

I need to sort the designation in hai array. I tried like this, but not working

db.collection.find({_id:ObjectId("12345")}).sort(hai:-1)
db.collection.find({_id:ObjectId("12345")}).sort(hai.designation:-1)

Can anyone please help, Thanks in advance

ShivaGaire
  • 2,283
  • 1
  • 20
  • 31

2 Answers2

0

You have to unwind array first then you can able to sort data.

ref link : Sort array

Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
0

The sort function expects an object like this (note the brackets in sort):

db.collection.find({_id:ObjectId("12345")}).sort({hai:-1})

or

db.collection.find({_id:ObjectId("12345")}).sort({"hai.designation":-1})

Also note if your sort is on a nested object then you need to use quotes around your key.

Aside: If you dont use the pipeline i.e. complex queries then you don't need to use unwind.

LongHike
  • 4,016
  • 4
  • 37
  • 76