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": "[email protected]",
  "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": "[email protected]",
   "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"
      }
    ]
 }
1
  • to achieve your desire result, I think you should use the aggregation framework Commented May 17, 2018 at 14:56

1 Answer 1

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"
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

2 Comments

this works fine but what about email and fullName, how to get them in the in response.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.