1

how can I sort addressBook.default in descending order when I want to select document with id.My sample structure (based on my model) below:

{  
  "_id" : ObjectId("9afd8416e7913223b09a89333"),
  "email": "abc@gmail.com",
  "fullName": "william",
  "addressBook": [
     {
       "_id": ObjectId("5afd8416e7913223b09a89333"),
       "default ": 1,
       "country": "hong kong"
     },
     {
       "_id": ObjectId("6afd8416e7913223b09a89333"),
       "default ": 0,
       "country": "india"
     },
     {
       "_id": ObjectId("7afd8416e7913223b09a89333"),
       "default ": 1,
       "country": "thailand"
     },
  ]
}

I tried something like this with findByID() and sort() function but I can get my desire result.

WebsiteUser.findById(req.user.id).sort('-addressBook.default').exec(function(err,result){
});

My desire result that I want when I select a document with document id:

 {  
   "_id" : ObjectId("9afd8416e7913223b09a89333"),
   "email": "abc@gmail.com",
   "fullName": "william",
   "addressBook": [
      {
        "_id": ObjectId("5afd8416e7913223b09a89333"),
        "default ": 1,
         "country": "hong kong"
      },
      {
        "_id": ObjectId("7afd8416e7913223b09a89333"),
        "default ": 1,
        "country": "thailand"
      },
      {
        "_id": ObjectId("6afd8416e7913223b09a89333"),
        "default ": 0,
        "country": "india"
      }
    ]
 }
Ashh
  • 44,693
  • 14
  • 105
  • 132

1 Answers1

1

You need to first $unwind the addressBook and then apply sort on default

db.collection.aggregate([
  {
    "$unwind": "$addressBook"
  },
  {
    "$sort": {
      "addressBook.default": 1
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "addressBook": {
        "$push": "$addressBook"
      }
    }
  }
])
Ashh
  • 44,693
  • 14
  • 105
  • 132