As autocomplete does not work on arrays or documents inside arrays (which is what the locations field consists of), we need to create an extra string field for this purpose. We already have our special _searchable member, so we add it there.
Migration
Run this script once on the current database:
use com\mongodb\MongoConnection;
use util\cmd\Console;
$conn= new MongoConnection('mongodb+srv://[user]:[pass]@dialog.[id].mongodb.net/');
$collection= $conn->collection('dialog.entries');
foreach ($collection->find() as $entry) {
Console::writeLine('> ', $entry['title']);
// Create _searchable.suggest
$suggest= '';
foreach ($entry['locations'] as $location) {
$suggest.= ' '.$location['name'];
}
$collection->update($entry->id(), ['$set' => [
'_searchable' => $entry['_searchable'] + ['suggest' => trim($suggest)]
]]);
}
Index definition
This is how the search index needs to be defined in MongoDB Atlas:
Change
Before:
After:
The precedence is as follows:
Implementation
As autocomplete does not work on arrays or documents inside arrays (which is what the locations field consists of), we need to create an extra string field for this purpose. We already have our special
_searchable
member, so we add it there.Migration
Run this script once on the current database:
Index definition
This is how the search index needs to be defined in MongoDB Atlas:
Note: The
_searchable.dynamic
key is important for the thing to work - unfortunately, the visual editor does not let you edit it like that!