Based off your description and correct me if I am wrong, the baseScore
is an independent score calculated outside of Atlas search. Because of this, I don’t believe it’s possible to combine the Atlas search scoring with the baseScore
field you’ve mentioned to create the custom sorting you are after without use of additional aggregation stages. I assume you wanted all of this done alone in the $search
stage for performance reasons maybe.
However, does the following example perhaps look a bit closer to what you’re after? I have a possible workaround, although i’m not entirely sure if it works for your use case, which uses the near
operator with an origin
of 1 (Let’s say this is the baseScore
we want to be closest to for sorting):
score> db.collection.aggregate(
[
{
'$search': {
index: 'textindex',
compound: {
should: [
{
autocomplete: {
path: 'textField',
query: 'ba',
score: { boost: { value: 2 } }
}
},
{ near: { path: 'baseScore', origin: 1, pivot: 0.1 } }
]
}
}
},
{
'$project': {
_id: 1,
baseScore: 1,
textField: 1,
searchScore: { '$meta': 'searchScore' }
}
}
])
Output (which includes the document with _id: 1
):
[
{
_id: 8,
textField: 'Banana 7',
baseScore: 0.7,
searchScore: 0.5457944273948669
},
{
_id: 7,
textField: 'Banana 6',
baseScore: 0.6,
searchScore: 0.495794415473938
},
{
_id: 6,
textField: 'Banana 5',
baseScore: 0.5,
searchScore: 0.46246111392974854
},
{
_id: 5,
textField: 'Banana 4',
baseScore: 0.4,
searchScore: 0.43865156173706055
},
{
_id: 4,
textField: 'Banana 3',
baseScore: 0.3,
searchScore: 0.42079442739486694
},
{
_id: 3,
textField: 'Banana 2',
baseScore: 0.2,
searchScore: 0.40690553188323975
},
{
_id: 2,
baseScore: 0.2,
textField: 'Banana',
searchScore: 0.3748180866241455
},
{
_id: 1,
baseScore: 0.5,
textField: 'Apple',
searchScore: 0.1666666716337204
}
]
I added a few extra documents as I was trying to understand how to achieve that ordering you were after but perhaps this approach won’t work for your data set / use case.