If you're looking to manipulate your data in a specific way, consider utilizing the aggregation framework. This will allow you to reformat your data for sorting purposes. Take a look at the example aggregation query below:
db.yourCollection.aggregate(
[
{$project:
{
first: 1,
rest: {$cond: [{$eq: ['$middle', '']}, '$last', '$middle']},
isMiddle: {$cond: [{$eq: ['$middle', '']}, false, true]}
}
},
{$sort: {rest: 1}},
{$project:
{
first: 1,
middle: {$cond: ['$isMiddle', '$rest', '']},
last: {$cond: ['$isMiddle', '', '$rest']}
}
}
]
)
By using this aggregation method, you can achieve the desired sorting outcome:
{ "first" : "Some", "middle" : "A", "last" : "" }
{ "first" : "Some", "middle" : "B", "last" : "" }
{ "first" : "Some", "middle" : "", "last" : "C" }
{ "first" : "Some", "middle" : "D", "last" : "" }
The typical sorting process treats the keys 'middle' and 'last' as separate entities, leading to independent sorting. To overcome this limitation, combining them into a single key through aggregation is necessary.