Reputation: 1563
Let's say I have the following collection
Collection = [
{name: 'Ann'},
{name: 'Bob'},
{name: 'Cecil'},
{name: 'KEY: John'},
{name: 'KEY: Cecil'},
{name: 'Susan'},
{name: 'Zack'}
];
Is there any way to use sort
in MongoDB
so that I can have all Documents
that have their name
field start with KEY:
get returned first? And then I'd like the rest of the Collection
to be sorted how it currently is.
I.e
Collection = [
{name: 'KEY: John'},
{name: 'KEY: Cecil'},
{name: 'Ann'},
{name: 'Bob'},
{name: 'Cecil'},
{name: 'Susan'},
{name: 'Zack'}
];
From what I've read there's no way to do a custom sort in MongoDB. If not, is there a simple way to do this in JS using underscore
or some other library. I'd prefer that than the accepted answer here Sort an array to have specific items first in the array where another array(s) has to be built.
Any ideas?
Upvotes: 2
Views: 734
Reputation: 49975
You can use $addFields to evaluate new field your collection will be sorted by. The $indexOfBytes operator can be used to determine if string starts with KEY
:
db.collection.aggregate([
{
$addFields: {
startsWithKey: { $eq: [ { $indexOfBytes: [ "$name", "KEY", 0 ] } ]}
}
},
{
$sort: {
startsWithKey: -1
}
}
])
Upvotes: 3