0

I am creating a NodeJS application and I want to sort contacts by last name. The problem is the name part must be saved as one string and when I use the sort function in MongoDB, the defaults are ascending or descending. Is it possible to create a custom sort? For example, if the information is

[
    {
        _id: "565c9f1ad5015e516ea99b91",
        name: "David Li"
    },
    {
        _id: "56642c73b35adedf4fad6c30",
        name: "George Chan"
    }
]

how can I sort it by the last name?

Currently I am sorting like this:

var options = {
    sort: "name"
};

collection.find({}, options, function(err, cursor) {
    res.json(cursor);
});
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
Geoffry
  • 25
  • 3

1 Answers1

0

With the data structure you have right now, you cannot do that. What you should do is, in addition to the full name field, have first name and last name as separate fields:

[
    {
        _id: "565c9f1ad5015e516ea99b91",
        fullName: "David Li",
        firstName: "David",
        lastName: "Li"
    },
    {
        _id: "56642c73b35adedf4fad6c30",
        fullName: "George Chan",
        firstName: "George",
        lastName: "Chan"

    }
]

Then you can easily sort by lastName:

collection.find({}, { sort: "lastName" }, function(err, cursor) {
    res.json(cursor);
});
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
  • The question explicitly stated "The problem is the name part must be saved as one string". – Philipp Dec 11 '15 at 12:21
  • Thank you for the suggestion. I will try to add the last name field and sort using that. – Geoffry Dec 11 '15 at 12:36
  • 1
    @Geoffry If you need to justify the new field to the stakeholders, you could argument that not all cultures put their family-names last, so that new field also says which name is the surname. Japanese, for example, put their surnames first and their given names last. – Philipp Dec 11 '15 at 12:42