[ad_1]
I have the following collections.
interface PartnerOrganization extends Document {
retailLocations?: RetailLocations[];
}
interface RetailLocation extends Document {
location: {
type: string;
coordinates: [number];
};
}
RetailLocation has an appropriate index setup, and I can successfully run aggregate queries such as the following
const retailLocation = await RetailLocation.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: [searchInput.longitude, searchInput.latitude] },
distanceField: 'dist.calculated',
maxDistance: Number(searchInput.radius),
includeLocs: 'dist.location',
spherical: true,
},
},
]);
I would like to be able to write an aggregate pipeline which uses a $geoNear
aggregate function, against PartnerOrganizations.
The overall goal being that I can do a search for PartnerOrganizations that match certain $search
(I am using the $search
aggregate) criteria as well as location criteria.
The issue I am having is that $geoNear
needs to be the first step in the aggregate pipeline, and as such retailLocations
hasn’t been populated at that stage. I have tested it out with $lookups
, but doing anything before the $geoNear
stage will cause a Mongo error similar to this –
Basically, my ‘dream query’ if you will, is something like this
const retailLocation = await PartnerOrganization.aggregate([
{
$lookup: {
from: 'retaillocations',
localField: 'retailLocations',
foreignField: '_id',
as: 'retailLocations',
},
},
{
$geoNear: {
key: 'retailLocations.location',
near: { type: 'Point', coordinates: [searchInput.longitude, searchInput.latitude] },
distanceField: 'dist.calculated',
maxDistance: Number(searchInput.radius),
includeLocs: 'dist.location',
spherical: true,
},
},
{
$search: {
index: 'Partner Organizations',
text: {
query: `*${searchInput.text}*`,
path: ['companyName', 'instagramBio', 'ogDescription'],
},
},
}
]);
But just not sure if this is possible, or if i have to do separate queries to make it work, then filter/map between the results. Just for claritys sake – I am using Linked Documents, not embedded – you can see what that looks like in Compass below.
[ad_2]