I’m struggling with the follow problem.
I’m making an aggregation pipeline (testing in Compass) to find 10 places near a geolocation (geoNear).
I also would like to know if those places fit within a polygon (geoWithin), however the result shouldn’t be limited by the fact that those places fit in that polygon.
That’s the struggle I have.
My need:
- Run geoNear
- Add a field “is_in_polygon” based on a geoWithin query.
(however I can’t figure out how to use $addField in combination with $match) - sort the results on “is_in_polygon”: true
- limit the results to 12.
In the case nothing is within the polygon I still would like to get 12 results back.
In the case only 6 out of 12 are within the polygon, I would like to get 12 results back, the first 6 with is_in_polygon: true, the other 6 with is_in_polygon: false
I would like to do this in one pipeline.
I was thinking in working with $facet, however $geoNear cannot be used within $facet, it always has to be the first stage in the pipeline.
Is it possible to use $addField (or $set, $project) based on a $match (query) outcome?
Is it possible to sort on that boolean field (so results with that specific field come first.
Below my current pipeline.
[{
$geoNear: {
near: {
type: 'Point',
coordinates: [
5.092047,
51.984694
]
},
key: 'geo',
spherical: true,
distanceField: 'dist',
query: {
access: {
$ne: 'quests_only'
}
}
}
}, {
$match: {
geo: {
$geoWithin: {
$geometry: {
type: 'Polygon',
coordinates: [
[
[
7.02324,
52.3444473
],
[
6.5975198,
52.3712859
],
[
6.4958963,
52.1763364
],
[
6.9133767,
52.1544352
],
[
7.02324,
52.3444473
]
]
]
}
}
}
}
}, {
$limit: 12
}]