Hi guys! I’m trying to make a autocomplete feature which needs to search within multiple fields. Some fields are in the same collection but other fields are in another collection. I already have a $search index in these two collections, but I ran intro multi problems.
Basically I need to retrieve all documents in Restaurant that matches a textSearch by name, alias, and a field name from another collection Products. These 3 searches has to be concatenated by an $or .
The model is the following:
type Restaurant {
_id: ObjectId;
name: String;
alias: string;
}
type Product {
_id: String;
name: String;
restaurantId: ObjectId;
}
Right now I have something like this:
let aggregatePipeline = [] as PipelineStage[];
if (!!textSearch) {
aggregatePipeline.push({
$lookup: {
from: ProductModel.collection.name,
localField: '_id',
foreignField: 'restaurantId',
pipeline: [
{
$search: {
compound: {
should: [
{
autocomplete: {
query: textSearch,
path: 'name',
},
},
{
autocomplete: {
query: textSearch,
path: 'type',
},
},
],
},
},
}
],
as: 'products',
},
});
// I don't know how to do this with $search
aggregatePipeline.push({
$match: {
$or: [
{ products: { $ne: [] } },
{ aliasFilter: { $regex: new RegExp(`.*${textSearch}.*`) } },
{ name: { $regex: new RegExp(`.*${textSearch}.*`) } },
],
},
});
}
As you can see I’m doing a $lookup to view all the Product that matches that string and then checking if that result is not an empty array. That will be concatenate with some basic search by $regex because I don’t know how to concatenate the search within products and restaurants.
Could someone have a look in case I’m doing completely random? Any hints on how to use $search by fields from other collections will be appreciated!
Thanks!